diff --git a/.github/ISSUE_TEMPLATE/bug-report.yml b/.github/ISSUE_TEMPLATE/bug-report.yml index feb074b2a7d..e988712055a 100644 --- a/.github/ISSUE_TEMPLATE/bug-report.yml +++ b/.github/ISSUE_TEMPLATE/bug-report.yml @@ -60,19 +60,21 @@ body: label: Anything else? description: | Links? References? Anything that will give us more context about the issue you are encountering! - - Tip: You can attach images or log files by clicking this area to highlight it and then dragging files in. + _Tip: You can attach images or log files by clicking this area to highlight it and then dragging files in._ validations: required: false - type: dropdown id: affected-versions attributes: label: Affected Versions - description: What versions of DNN are you running? + description: | + What version of DNN are you running? + **NOTE:** _If your version is not listed, please upgrade to the latest version. If you cannot upgrade at this time, please open a [Discussion](https://github.com/dnnsoftware/Dnn.Platform/discussions) instead._ multiple: true options: + - 9.12.0 (latest release) + - 9.13.0 (release candidate) - 10.0.0 (alpha) - - 9.11.2 (latest release) validations: required: true - type: dropdown diff --git a/.github/workflows/image-actions.yml b/.github/workflows/image-actions.yml index 421acb4072b..585ad067f33 100644 --- a/.github/workflows/image-actions.yml +++ b/.github/workflows/image-actions.yml @@ -22,7 +22,7 @@ jobs: runs-on: ubuntu-latest steps: - name: Checkout Repo - uses: actions/checkout@v3 + uses: actions/checkout@v4 - name: Compress Images id: compress_images diff --git a/.github/workflows/open-merged-pr-to-future.yml b/.github/workflows/open-merged-pr-to-future.yml index 65191c5c326..edf6a0139fd 100644 --- a/.github/workflows/open-merged-pr-to-future.yml +++ b/.github/workflows/open-merged-pr-to-future.yml @@ -11,7 +11,7 @@ jobs: runs-on: ubuntu-latest if: ${{ github.event.pull_request.merged }} steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 - uses: peterjgrainger/action-create-branch@v2.4.0 env: diff --git a/.github/workflows/updateVersions.yml b/.github/workflows/updateVersions.yml index 6d3034ec86a..59ad51ab441 100644 --- a/.github/workflows/updateVersions.yml +++ b/.github/workflows/updateVersions.yml @@ -7,7 +7,7 @@ jobs: runs-on: ubuntu-latest if: ${{ github.event.ref_type == 'branch' && startsWith(github.event.ref, 'release/') }} steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 - name: Get the release branch version uses: valadas/get-release-branch-version@v1.0.1 diff --git a/.gitignore b/.gitignore index 65f426d862b..371f696ce34 100644 --- a/.gitignore +++ b/.gitignore @@ -145,3 +145,6 @@ yarn-error.log /Build/bin/ /.dotnet/ /Build/Tools/ + +/DotNetNuke.Internal.SourceGenerators/bin/ +/DNN Platform/Tests/DotNetNuke.Tests.SourceGenerators/Snapshots/*.received.* diff --git a/Build/Build.csproj b/Build/Build.csproj index e5a763a15dd..4fae321365b 100644 --- a/Build/Build.csproj +++ b/Build/Build.csproj @@ -14,18 +14,18 @@ - - - - - - + + + + + + - + - + all runtime; build; native; contentfiles; analyzers; buildtransitive diff --git a/Build/Lifetime.cs b/Build/Lifetime.cs index cb574da59eb..82c3831958c 100644 --- a/Build/Lifetime.cs +++ b/Build/Lifetime.cs @@ -14,7 +14,7 @@ namespace DotNetNuke.Build public sealed class Lifetime : FrostingLifetime { /// - public override void Setup(Context context) + public override void Setup(Context context, ISetupContext setupContext) { context.IsRunningInCI = context.HasEnvironmentVariable("TF_BUILD"); context.Information("Is Running in CI : {0}", context.IsRunningInCI); diff --git a/Build/Tasks/packaging.json b/Build/Tasks/packaging.json index edcf5bd7403..31f996bdd4a 100644 --- a/Build/Tasks/packaging.json +++ b/Build/Tasks/packaging.json @@ -19,6 +19,7 @@ "/bin/Dnn.PersonaBar.*", "/bin/DotNetNuke.Authentication.*", "/bin/DotNetNuke.Modules.*", + "/bin/DotNetNuke.Internal.*", "/bin/DotNetNuke.Web.Deprecated.dll", "/bin/DotNetNuke.Website.Deprecated.dll", "/bin/System.IdentityModel.Tokens.Jwt.*", diff --git a/Build/Tasks/thirdparty.json b/Build/Tasks/thirdparty.json index 02980cfe3bf..575986874cd 100644 --- a/Build/Tasks/thirdparty.json +++ b/Build/Tasks/thirdparty.json @@ -1,44 +1,64 @@ -[ - { - "name": "jQuery", - "folder": "DNN Platform/JavaScript Libraries/jQuery/", - "destination": "Install/JavaScriptLibrary" - }, - { - "name": "jQueryMigrate", - "folder": "DNN Platform/JavaScript Libraries/jQueryMigrate/", - "destination": "Install/JavaScriptLibrary" - }, - { - "name": "jQueryUI", - "folder": "DNN Platform/JavaScript Libraries/jQueryUI/", - "destination": "Install/JavaScriptLibrary" - }, - { - "name": "Knockout", - "folder": "DNN Platform/JavaScript Libraries/Knockout/", - "destination": "Install/JavaScriptLibrary" - }, - { - "name": "KnockoutMapping", - "folder": "DNN Platform/JavaScript Libraries/KnockoutMapping/", - "destination": "Install/JavaScriptLibrary" - }, - { - "name": "Selectize", - "folder": "DNN Platform/JavaScript Libraries/Selectize/", - "destination": "Install/JavaScriptLibrary" - }, - { - "name": "Microsoft.CodeDom.Providers.DotNetCompilerPlatform", - "folder": "DNN Platform/Components/Microsoft.CodeDom.Providers.DotNetCompilerPlatform/", - "destination": "Install/Library", - "extension": "resources" - }, - { - "name": "MicrosoftFileSystemGlobbing", - "folder": "DNN Platform/Components/Microsoft.Extensions.FileSystemGlobbing/", - "destination": "Install/Library", - "excludes": [ "**/*.xml" ] - } -] +[ + { + "name": "DnnPlugins", + "folder": "DNN Platform/JavaScript Libraries/DnnPlugins/", + "destination": "Install/JavaScriptLibrary" + }, + { + "name": "HoverIntent", + "folder": "DNN Platform/JavaScript Libraries/HoverIntent/", + "destination": "Install/JavaScriptLibrary" + }, + { + "name": "jQuery", + "folder": "DNN Platform/JavaScript Libraries/jQuery/", + "destination": "Install/JavaScriptLibrary" + }, + { + "name": "jQuery.Fileupload", + "folder": "DNN Platform/JavaScript Libraries/jQuery.Fileupload/", + "destination": "Install/JavaScriptLibrary" + }, + { + "name": "jQuery.iframe-transport", + "folder": "DNN Platform/JavaScript Libraries/jQuery.iframe-transport/", + "destination": "Install/JavaScriptLibrary" + }, + { + "name": "jQueryMigrate", + "folder": "DNN Platform/JavaScript Libraries/jQueryMigrate/", + "destination": "Install/JavaScriptLibrary" + }, + { + "name": "jQueryUI", + "folder": "DNN Platform/JavaScript Libraries/jQueryUI/", + "destination": "Install/JavaScriptLibrary" + }, + { + "name": "Knockout", + "folder": "DNN Platform/JavaScript Libraries/Knockout/", + "destination": "Install/JavaScriptLibrary" + }, + { + "name": "KnockoutMapping", + "folder": "DNN Platform/JavaScript Libraries/KnockoutMapping/", + "destination": "Install/JavaScriptLibrary" + }, + { + "name": "Selectize", + "folder": "DNN Platform/JavaScript Libraries/Selectize/", + "destination": "Install/JavaScriptLibrary" + }, + { + "name": "Microsoft.CodeDom.Providers.DotNetCompilerPlatform", + "folder": "DNN Platform/Components/Microsoft.CodeDom.Providers.DotNetCompilerPlatform/", + "destination": "Install/Library", + "extension": "resources" + }, + { + "name": "MicrosoftFileSystemGlobbing", + "folder": "DNN Platform/Components/Microsoft.Extensions.FileSystemGlobbing/", + "destination": "Install/Library", + "excludes": [ "**/*.xml" ] + } +] diff --git a/Build/Tasks/unversionedManifests.txt b/Build/Tasks/unversionedManifests.txt index 5ed96c08ad5..48ff39fc92b 100644 --- a/Build/Tasks/unversionedManifests.txt +++ b/Build/Tasks/unversionedManifests.txt @@ -3,5 +3,8 @@ DNN Platform/Components/Microsoft.*/**/*.dnn DNN Platform/Components/Newtonsoft/*.dnn DNN Platform/Components/WebFormsMvp/*.dnn DNN Platform/Components/SharpZipLib/*.dnn -DNN Platform/JavaScript Libraries/**/*.dnn +DNN Platform/JavaScript Libraries/HoverIntent/*.dnn +DNN Platform/JavaScript Libraries/jQuery*/*.dnn +DNN Platform/JavaScript Libraries/Knockout*/*.dnn +DNN Platform/JavaScript Libraries/Selectize/*.dnn Temp/**/*.dnn \ No newline at end of file diff --git a/Build/Tools/NuGet/DotNetNuke.WebApi.nuspec b/Build/Tools/NuGet/DotNetNuke.WebApi.nuspec index a2df755b3dd..11fc7752ad0 100644 --- a/Build/Tools/NuGet/DotNetNuke.WebApi.nuspec +++ b/Build/Tools/NuGet/DotNetNuke.WebApi.nuspec @@ -17,7 +17,7 @@ - + diff --git a/DNN Platform/Admin Modules/Dnn.Modules.Console/Dnn.Modules.Console.csproj b/DNN Platform/Admin Modules/Dnn.Modules.Console/Dnn.Modules.Console.csproj index b1804ed3691..97d47a456a3 100644 --- a/DNN Platform/Admin Modules/Dnn.Modules.Console/Dnn.Modules.Console.csproj +++ b/DNN Platform/Admin Modules/Dnn.Modules.Console/Dnn.Modules.Console.csproj @@ -36,7 +36,7 @@ bin\Dnn.Modules.Console.XML - 7 + latest true @@ -49,7 +49,7 @@ bin\Dnn.Modules.Console.XML - 7 + latest true diff --git a/DNN Platform/Connectors/Azure/AzureConnector.dnn b/DNN Platform/Connectors/Azure/AzureConnector.dnn index bae8ef3941b..6a2e9a16839 100644 --- a/DNN Platform/Connectors/Azure/AzureConnector.dnn +++ b/DNN Platform/Connectors/Azure/AzureConnector.dnn @@ -2,7 +2,7 @@ Dnn Azure Connector - The Azure Connector allows you to integrate Azure as your commenting solution with the Publisher module. + The Azure Connector allows you to create folders mapped to Azure Storage accounts. ~/DesktopModules/Connectors/Azure/Images/icon-azure-32px.png 09.02.00 diff --git a/DNN Platform/Connectors/Azure/Dnn.AzureConnector.csproj b/DNN Platform/Connectors/Azure/Dnn.AzureConnector.csproj index 830988e61fd..215371e8214 100644 --- a/DNN Platform/Connectors/Azure/Dnn.AzureConnector.csproj +++ b/DNN Platform/Connectors/Azure/Dnn.AzureConnector.csproj @@ -27,8 +27,9 @@ prompt 4 bin\Dnn.AzureConnector.xml - 7 + latest 1591 + true pdbonly @@ -39,7 +40,8 @@ 4 bin\Dnn.AzureConnector.xml 1591 - 7 + latest + true true @@ -50,7 +52,7 @@ prompt 4 bin\Dnn.AzureConnector.xml - 7 + latest 1591 @@ -62,7 +64,7 @@ 4 bin\Dnn.AzureConnector.xml 1591 - 7 + latest @@ -70,8 +72,7 @@ ..\..\Components\WindowsAzure\Microsoft.WindowsAzure.Storage.dll - ..\..\..\packages\Newtonsoft.Json.13.0.2\lib\net45\Newtonsoft.Json.dll - True + ..\..\..\packages\Newtonsoft.Json.13.0.3\lib\net45\Newtonsoft.Json.dll diff --git a/DNN Platform/Connectors/Azure/packages.config b/DNN Platform/Connectors/Azure/packages.config index 70edc1fe6ea..35a1f217f49 100644 --- a/DNN Platform/Connectors/Azure/packages.config +++ b/DNN Platform/Connectors/Azure/packages.config @@ -4,6 +4,6 @@ - + \ No newline at end of file diff --git a/DNN Platform/Connectors/GoogleAnalytics/App_LocalResources/SharedResources.resx b/DNN Platform/Connectors/GoogleAnalytics/App_LocalResources/SharedResources.resx index ec1a243f348..5d88422001c 100644 --- a/DNN Platform/Connectors/GoogleAnalytics/App_LocalResources/SharedResources.resx +++ b/DNN Platform/Connectors/GoogleAnalytics/App_LocalResources/SharedResources.resx @@ -121,7 +121,7 @@ Delete Connection - Google Analytics Core Connector + Google Analytics (Legacy UA) Connector Track for Administrators: diff --git a/DNN Platform/Connectors/GoogleAnalytics/Dnn.GoogleAnalyticsConnector.csproj b/DNN Platform/Connectors/GoogleAnalytics/Dnn.GoogleAnalyticsConnector.csproj index 30793d3692f..3386535d9ad 100644 --- a/DNN Platform/Connectors/GoogleAnalytics/Dnn.GoogleAnalyticsConnector.csproj +++ b/DNN Platform/Connectors/GoogleAnalytics/Dnn.GoogleAnalyticsConnector.csproj @@ -26,7 +26,7 @@ prompt 4 bin\DNN.Connectors.GoogleAnalytics.xml - 7 + latest 1591 true @@ -39,7 +39,8 @@ 4 bin\DNN.Connectors.GoogleAnalytics.xml 1591 - 7 + latest + true true @@ -50,7 +51,7 @@ prompt 4 bin\DNN.Connectors.GoogleAnalytics.xml - 7 + latest 1591 @@ -62,12 +63,11 @@ 4 bin\DNN.Connectors.GoogleAnalytics.xml 1591 - 7 + latest - ..\..\..\packages\Newtonsoft.Json.13.0.2\lib\net45\Newtonsoft.Json.dll - True + ..\..\..\packages\Newtonsoft.Json.13.0.3\lib\net45\Newtonsoft.Json.dll diff --git a/DNN Platform/Connectors/GoogleAnalytics/GoogleAnalyticsConnector.cs b/DNN Platform/Connectors/GoogleAnalytics/GoogleAnalyticsConnector.cs index 16e39e018ad..3fc0c5fc8b7 100644 --- a/DNN Platform/Connectors/GoogleAnalytics/GoogleAnalyticsConnector.cs +++ b/DNN Platform/Connectors/GoogleAnalytics/GoogleAnalyticsConnector.cs @@ -16,7 +16,7 @@ namespace DNN.Connectors.GoogleAnalytics /// Connector to provide configuration for Google Analytics support. public class GoogleAnalyticsConnector : IConnector { - private const string DefaultDisplayName = "Google Analytics"; + private const string DefaultDisplayName = "Google Analytics (Legacy UA)"; private string displayName; diff --git a/DNN Platform/Connectors/GoogleAnalytics/GoogleAnalyticsConnector.dnn b/DNN Platform/Connectors/GoogleAnalytics/GoogleAnalyticsConnector.dnn index b79d4b764f7..99febd4093c 100644 --- a/DNN Platform/Connectors/GoogleAnalytics/GoogleAnalyticsConnector.dnn +++ b/DNN Platform/Connectors/GoogleAnalytics/GoogleAnalyticsConnector.dnn @@ -1,8 +1,8 @@ - Google Analytics Connector - Configure your sites Google Analytics settings. + Google Analytics (Legacy UA) Connector + Configure your site's Google Analytics settings using Universal Analytics. ~/DesktopModules/Connectors/GoogleAnalytics/Images/GoogleAnalytics_32X32_Standard.png 09.02.00 diff --git a/DNN Platform/Connectors/GoogleAnalytics/packages.config b/DNN Platform/Connectors/GoogleAnalytics/packages.config index 609eb5daefd..913da1b07de 100644 --- a/DNN Platform/Connectors/GoogleAnalytics/packages.config +++ b/DNN Platform/Connectors/GoogleAnalytics/packages.config @@ -2,6 +2,6 @@ - + \ No newline at end of file diff --git a/DNN Platform/Connectors/GoogleAnalytics4/Dnn.GoogleAnalytics4Connector.csproj b/DNN Platform/Connectors/GoogleAnalytics4/Dnn.GoogleAnalytics4Connector.csproj index 24798b94e2c..de8a706960e 100644 --- a/DNN Platform/Connectors/GoogleAnalytics4/Dnn.GoogleAnalytics4Connector.csproj +++ b/DNN Platform/Connectors/GoogleAnalytics4/Dnn.GoogleAnalytics4Connector.csproj @@ -1,137 +1,137 @@ - - - - true - - - Debug - AnyCPU - 8.0.30703 - 2.0 - {94E12995-181A-4114-90C7-3F9557F28DE7} - Library - Properties - DNN.Connectors.GoogleAnalytics4 - DNN.Connectors.GoogleAnalytics4 - v4.7.2 - 512 - - - - true - full - false - bin - DEBUG;TRACE - prompt - 4 - bin\DNN.Connectors.GoogleAnalytics4.xml - 7 - 1591 - true - - - pdbonly - true - bin - TRACE - prompt - 4 - bin\DNN.Connectors.GoogleAnalytics4.xml - 1591 - 7 - - - true - full - false - bin - DEBUG;TRACE;CLOUD;CLOUD_DEBUG - prompt - 4 - bin\DNN.Connectors.GoogleAnalytics4.xml - 7 - 1591 - - - pdbonly - true - bin - TRACE;CLOUD;CLOUD_RELEASE - prompt - 4 - bin\DNN.Connectors.GoogleAnalytics4.xml - 1591 - 7 - - - - ..\..\..\packages\Newtonsoft.Json.13.0.2\lib\net45\Newtonsoft.Json.dll - True - - - - - - - ..\..\..\packages\Microsoft.AspNet.WebApi.Client.5.2.9\lib\net45\System.Net.Http.Formatting.dll - - - - ..\..\..\packages\Microsoft.AspNet.WebApi.Core.5.2.9\lib\net45\System.Web.Http.dll - - - - - - - - - stylecop.json - - - - - - - - - - {3cd5f6b8-8360-4862-80b6-f402892db7dd} - DotNetNuke.Instrumentation - - - {ee1329fe-fd88-4e1a-968c-345e394ef080} - DotNetNuke.Web - - - {6b29aded-7b56-4484-bea5-c0e09079535b} - DotNetNuke.Library - - - {b267ce88-dffc-4bd8-9962-319e79c52526} - DotNetNuke.Providers.FolderProviders - - - - - - - - - - - - - - - - - - - - - - - + + + + true + + + Debug + AnyCPU + 8.0.30703 + 2.0 + {94E12995-181A-4114-90C7-3F9557F28DE7} + Library + Properties + DNN.Connectors.GoogleAnalytics4 + DNN.Connectors.GoogleAnalytics4 + v4.7.2 + 512 + + + + true + full + false + bin + DEBUG;TRACE + prompt + 4 + bin\DNN.Connectors.GoogleAnalytics4.xml + latest + 1591 + true + + + pdbonly + true + bin + TRACE + prompt + 4 + bin\DNN.Connectors.GoogleAnalytics4.xml + 1591 + latest + true + + + true + full + false + bin + DEBUG;TRACE;CLOUD;CLOUD_DEBUG + prompt + 4 + bin\DNN.Connectors.GoogleAnalytics4.xml + latest + 1591 + + + pdbonly + true + bin + TRACE;CLOUD;CLOUD_RELEASE + prompt + 4 + bin\DNN.Connectors.GoogleAnalytics4.xml + 1591 + latest + + + + ..\..\..\packages\Newtonsoft.Json.13.0.3\lib\net45\Newtonsoft.Json.dll + + + + + + + ..\..\..\packages\Microsoft.AspNet.WebApi.Client.5.2.9\lib\net45\System.Net.Http.Formatting.dll + + + + ..\..\..\packages\Microsoft.AspNet.WebApi.Core.5.2.9\lib\net45\System.Web.Http.dll + + + + + + + + + stylecop.json + + + + + + + + + + {3cd5f6b8-8360-4862-80b6-f402892db7dd} + DotNetNuke.Instrumentation + + + {ee1329fe-fd88-4e1a-968c-345e394ef080} + DotNetNuke.Web + + + {6b29aded-7b56-4484-bea5-c0e09079535b} + DotNetNuke.Library + + + {b267ce88-dffc-4bd8-9962-319e79c52526} + DotNetNuke.Providers.FolderProviders + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/DNN Platform/Connectors/GoogleAnalytics4/GoogleAnalytics4Connector.dnn b/DNN Platform/Connectors/GoogleAnalytics4/GoogleAnalytics4Connector.dnn index e51e0e3126d..87962eb5dc2 100644 --- a/DNN Platform/Connectors/GoogleAnalytics4/GoogleAnalytics4Connector.dnn +++ b/DNN Platform/Connectors/GoogleAnalytics4/GoogleAnalytics4Connector.dnn @@ -2,7 +2,7 @@ Google Analytics 4 Connector - Configure your sites Google Analytics 4 settings. + Configure your site's Google Analytics 4 settings. ~/DesktopModules/Connectors/GoogleAnalytics4/Images/GoogleAnalytics4_32X32_Standard.png 09.02.00 diff --git a/DNN Platform/Connectors/GoogleAnalytics4/Images/GoogleAnalytics4_32X32_Standard.png b/DNN Platform/Connectors/GoogleAnalytics4/Images/GoogleAnalytics4_32X32_Standard.png index d5426ec46af..1dd97092253 100644 Binary files a/DNN Platform/Connectors/GoogleAnalytics4/Images/GoogleAnalytics4_32X32_Standard.png and b/DNN Platform/Connectors/GoogleAnalytics4/Images/GoogleAnalytics4_32X32_Standard.png differ diff --git a/DNN Platform/Connectors/GoogleAnalytics4/app.config b/DNN Platform/Connectors/GoogleAnalytics4/app.config index 6838e65ce66..c63cc7d0666 100644 --- a/DNN Platform/Connectors/GoogleAnalytics4/app.config +++ b/DNN Platform/Connectors/GoogleAnalytics4/app.config @@ -1,27 +1,27 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/DNN Platform/Connectors/GoogleAnalytics4/packages.config b/DNN Platform/Connectors/GoogleAnalytics4/packages.config index 0500291e746..913da1b07de 100644 --- a/DNN Platform/Connectors/GoogleAnalytics4/packages.config +++ b/DNN Platform/Connectors/GoogleAnalytics4/packages.config @@ -1,7 +1,7 @@ - - - - - - + + + + + + \ No newline at end of file diff --git a/DNN Platform/Connectors/GoogleTagManager/Dnn.GoogleTagManagerConnector.csproj b/DNN Platform/Connectors/GoogleTagManager/Dnn.GoogleTagManagerConnector.csproj index 140a2c43529..dba0b58db50 100644 --- a/DNN Platform/Connectors/GoogleTagManager/Dnn.GoogleTagManagerConnector.csproj +++ b/DNN Platform/Connectors/GoogleTagManager/Dnn.GoogleTagManagerConnector.csproj @@ -27,8 +27,9 @@ prompt 4 bin\DNN.Connectors.GoogleTagManager.xml - 7 + latest 1591 + true pdbonly @@ -39,8 +40,8 @@ 4 bin\DNN.Connectors.GoogleTagManager.xml 1591 - 7 - false + latest + true true @@ -51,7 +52,7 @@ prompt 4 bin\DNN.Connectors.GoogleTagManager.xml - 7 + latest 1591 @@ -63,12 +64,11 @@ 4 bin\DNN.Connectors.GoogleTagManager.xml 1591 - 7 + latest - ..\..\..\packages\Newtonsoft.Json.13.0.2\lib\net45\Newtonsoft.Json.dll - True + ..\..\..\packages\Newtonsoft.Json.13.0.3\lib\net45\Newtonsoft.Json.dll diff --git a/DNN Platform/Connectors/GoogleTagManager/GoogleTagManagerConnector.dnn b/DNN Platform/Connectors/GoogleTagManager/GoogleTagManagerConnector.dnn index 6537df34654..572dcb13eea 100644 --- a/DNN Platform/Connectors/GoogleTagManager/GoogleTagManagerConnector.dnn +++ b/DNN Platform/Connectors/GoogleTagManager/GoogleTagManagerConnector.dnn @@ -2,7 +2,7 @@ Google Tag Manager Connector - Configure your sites Google Tag Manager settings. + Configure your site's Google Tag Manager settings. ~/DesktopModules/Connectors/GoogleTagManager/Images/GoogleTagManager_32X32_Standard.png 09.02.00 diff --git a/DNN Platform/Connectors/GoogleTagManager/packages.config b/DNN Platform/Connectors/GoogleTagManager/packages.config index 609eb5daefd..913da1b07de 100644 --- a/DNN Platform/Connectors/GoogleTagManager/packages.config +++ b/DNN Platform/Connectors/GoogleTagManager/packages.config @@ -2,6 +2,6 @@ - + \ No newline at end of file diff --git a/DNN Platform/Controls/CountryListBox/CountryListBox.csproj b/DNN Platform/Controls/CountryListBox/CountryListBox.csproj index bfba6b31b61..fc5259fc8af 100644 --- a/DNN Platform/Controls/CountryListBox/CountryListBox.csproj +++ b/DNN Platform/Controls/CountryListBox/CountryListBox.csproj @@ -43,7 +43,7 @@ full AllRules.ruleset 1591 - 7 + latest true @@ -56,7 +56,7 @@ AllRules.ruleset 1591 true - 7 + latest true diff --git a/DNN Platform/Dnn.AuthServices.Jwt/Dnn.AuthServices.Jwt.csproj b/DNN Platform/Dnn.AuthServices.Jwt/Dnn.AuthServices.Jwt.csproj index f67a27227a3..8ed8afa7997 100644 --- a/DNN Platform/Dnn.AuthServices.Jwt/Dnn.AuthServices.Jwt.csproj +++ b/DNN Platform/Dnn.AuthServices.Jwt/Dnn.AuthServices.Jwt.csproj @@ -25,7 +25,7 @@ 4 1591 bin\Dnn.AuthServices.Jwt.XML - 7 + latest true @@ -37,13 +37,12 @@ 4 bin\Dnn.AuthServices.Jwt.XML 1591 - 7 + latest true - ..\..\packages\Newtonsoft.Json.13.0.2\lib\net45\Newtonsoft.Json.dll - True + ..\..\packages\Newtonsoft.Json.13.0.3\lib\net45\Newtonsoft.Json.dll diff --git a/DNN Platform/Dnn.AuthServices.Jwt/packages.config b/DNN Platform/Dnn.AuthServices.Jwt/packages.config index cbbb48782cc..ebefa5c93a0 100644 --- a/DNN Platform/Dnn.AuthServices.Jwt/packages.config +++ b/DNN Platform/Dnn.AuthServices.Jwt/packages.config @@ -4,7 +4,7 @@ - + \ No newline at end of file diff --git a/DNN Platform/DotNetNuke.Abstractions/DnnDeprecatedAttribute.cs b/DNN Platform/DotNetNuke.Abstractions/DnnDeprecatedAttribute.cs new file mode 100644 index 00000000000..82fa906c3b4 --- /dev/null +++ b/DNN Platform/DotNetNuke.Abstractions/DnnDeprecatedAttribute.cs @@ -0,0 +1,41 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information +namespace DotNetNuke.Internal.SourceGenerators; + +using System; +using System.Diagnostics; + +/// Marks a type or member as deprecated. +[Conditional("DNN_SOURCE_GENERATOR")] +public class DnnDeprecatedAttribute : Attribute +{ + /// Initializes a new instance of the class. + /// The major version in which the type or member was deprecated. + /// The minor version in which the type or member was deprecated. + /// The patch version in which the type or member was deprecated. + /// The suggested replacement or alternative. + public DnnDeprecatedAttribute(int majorVersion, int minorVersion, int patchVersion, string replacement) + { + this.MajorVersion = majorVersion; + this.MinorVersion = minorVersion; + this.PatchVersion = patchVersion; + this.Replacement = replacement; + this.RemovalVersion = majorVersion + 2; + } + + /// Gets the major version in which the type or member was deprecated. + public int MajorVersion { get; } + + /// Gets the minor version in which the type or member was deprecated. + public int MinorVersion { get; } + + /// Gets the patch version in which the type or member was deprecated. + public int PatchVersion { get; } + + /// Gets the suggested replacement or alternative. + public string Replacement { get; } + + /// Gets or sets the major version in which the type or member will be removed. + public int RemovalVersion { get; set; } +} diff --git a/DNN Platform/DotNetNuke.Abstractions/DotNetNuke.Abstractions.csproj b/DNN Platform/DotNetNuke.Abstractions/DotNetNuke.Abstractions.csproj index 22d03f6d033..53304f6e1b6 100644 --- a/DNN Platform/DotNetNuke.Abstractions/DotNetNuke.Abstractions.csproj +++ b/DNN Platform/DotNetNuke.Abstractions/DotNetNuke.Abstractions.csproj @@ -9,6 +9,7 @@ true + latest diff --git a/DNN Platform/DotNetNuke.Abstractions/Portals/IPortalSettings.cs b/DNN Platform/DotNetNuke.Abstractions/Portals/IPortalSettings.cs index 7096e6837fb..a4ca69cd77f 100644 --- a/DNN Platform/DotNetNuke.Abstractions/Portals/IPortalSettings.cs +++ b/DNN Platform/DotNetNuke.Abstractions/Portals/IPortalSettings.cs @@ -150,8 +150,7 @@ public interface IPortalSettings /// Gets a value indicating whether the Skin Widgets are enabled/supported. /// Defaults to True. - [Obsolete("This setting is no longer relevant as skin widgets are no longer supported. Scheduled for removal in v11.0.0")] - + [Obsolete("Deprecated in DotNetNuke 8.0.0. Skin widgets are no longer supported. Scheduled removal in v11.0.0.")] bool EnableSkinWidgets { get; } /// Gets a value indicating whether the content is localized. diff --git a/DNN Platform/DotNetNuke.DependencyInjection/DotNetNuke.DependencyInjection.csproj b/DNN Platform/DotNetNuke.DependencyInjection/DotNetNuke.DependencyInjection.csproj index 4e172c95e4b..f9d1437732c 100644 --- a/DNN Platform/DotNetNuke.DependencyInjection/DotNetNuke.DependencyInjection.csproj +++ b/DNN Platform/DotNetNuke.DependencyInjection/DotNetNuke.DependencyInjection.csproj @@ -36,6 +36,10 @@ + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + diff --git a/DNN Platform/DotNetNuke.DependencyInjection/Extensions/TypeExtensions.cs b/DNN Platform/DotNetNuke.DependencyInjection/Extensions/TypeExtensions.cs index cff6ea68dfb..0d4cf2aef31 100644 --- a/DNN Platform/DotNetNuke.DependencyInjection/Extensions/TypeExtensions.cs +++ b/DNN Platform/DotNetNuke.DependencyInjection/Extensions/TypeExtensions.cs @@ -4,78 +4,177 @@ namespace DotNetNuke.DependencyInjection.Extensions { using System; + using System.Collections.Generic; using System.Linq; using System.Reflection; + using System.Text; using DotNetNuke.Instrumentation; + using DotNetNuke.Internal.SourceGenerators; - /// - /// specific extensions to be used - /// in Dependency Injection invocations. - /// - public static class TypeExtensions + /// specific extensions to be used in Dependency Injection invocations. + public static partial class TypeExtensions { - /// - /// Safely Get all Types from the assembly. If there - /// is an error while retrieving the types it will - /// return an empty array of . - /// + /// Safely Get all Types from the assembly. If there is an error while retrieving the types it will return an empty array of . /// The assembly to retrieve all types from. /// An array of all in the given . /// This is obsolete because logging is not added. Please use the SafeGetTypes with the ILog parameter. - [Obsolete("Deprecated in DotNetNuke 9.9.0. Please use the SafeGetTypes overload with the ILog parameter. Scheduled removal in v11.0.0.")] - public static Type[] SafeGetTypes(this Assembly assembly) + [DnnDeprecated(9, 9, 0, "Please use the SafeGetTypes overload with the ILog parameter")] + public static partial Type[] SafeGetTypes(this Assembly assembly) { return assembly.SafeGetTypes(null); } - /// - /// Safely Get all Types from the assembly. If there - /// is an error while retrieving the types it will - /// return an empty array of . - /// - /// - /// The assembly to retrieve all types from. - /// - /// - /// A optional object. This will log any messages from the exception catching to the logs as an Error. - /// - /// - /// An array of all in the given . - /// - public static Type[] SafeGetTypes(this Assembly assembly, ILog logger = null) + /// Safely Get all Types from the assembly. If there is an error while retrieving the types it will return an empty array of . + /// The assembly to retrieve all types from. + /// A optional object. This will log issues loading the types. + /// An array of all in the given . + public static Type[] SafeGetTypes(this Assembly assembly, ILog logger) { - Type[] types = null; - try + var (types, exception) = assembly.GetTypesAndException(); + if (logger is null || exception is null) { - types = assembly.GetTypes(); + return types.ToArray(); } - catch (ReflectionTypeLoadException ex) + + if (exception is ReflectionTypeLoadException loadException) + { + var messageBuilder = BuildLoaderExceptionMessage( + new StringBuilder($"Unable to get all types for {assembly.FullName}, see exception for details").AppendLine(), + assembly, + loadException); + + logger.Warn(messageBuilder.ToString(), loadException); + } + else + { + logger.Error($"Unable to get any types for {assembly.FullName}, see exception for details", exception); + } + + return types.ToArray(); + } + + /// Safely get all types from all assemblies. + /// A sequence of all available instances, along with errors and warnings. + public static TypesResult SafeGetTypes() + { + return AppDomain.CurrentDomain.GetAssemblies() + .OrderBy(DotNetNukeFirstThenDnnThenOthers) + .ThenBy(assembly => assembly.FullName) + .SafeGetTypes(); + + static int DotNetNukeFirstThenDnnThenOthers(Assembly assembly) { - if (logger != null) + if (assembly.FullName.StartsWith("DotNetNuke", StringComparison.OrdinalIgnoreCase)) { - // The loaderexceptions will repeat. Need to get distinct messages here. - string distinctLoaderExceptions = string.Join( - Environment.NewLine, - ex.LoaderExceptions.Select(i => i.Message).Distinct().Select(i => $"- LoaderException: {i}")); + return 0; + } - logger.Error($"Unable to configure services for {assembly.FullName}, see exception for details {Environment.NewLine}{distinctLoaderExceptions}", ex); + if (assembly.FullName.StartsWith("DNN", StringComparison.OrdinalIgnoreCase)) + { + return 1; } - // Ensure that Dnn obtains all types that were loaded, ignoring the failure(s) - types = ex.Types.Where(x => x != null).ToArray(); + return 2; } - catch (Exception ex) + } + + /// Safely get all types from a set of assemblies. + /// The assemblies. + /// A sequence of all available instances, along with errors and warnings. + public static TypesResult SafeGetTypes(this IEnumerable assemblies) + { + var loadExceptions = new Dictionary(); + var otherExceptions = new Dictionary(); + var types = assemblies.SafeGetTypes(loadExceptions, otherExceptions); + return new TypesResult(types.ToList(), loadExceptions, otherExceptions); + } + + /// Logs the exceptions in of using . + /// The types result to log. + /// The logger. + public static void LogOtherExceptions(this TypesResult result, ILog logger) + { + if (logger is null) + { + return; + } + + foreach (var exceptionPair in result.OtherExceptions) { - if (logger != null) + var assembly = exceptionPair.Key; + var exception = exceptionPair.Value; + logger.Error($"Unable to get any types for {assembly.FullName}, see exception for details", exception); + } + } + + /// Builds a message to load for a collection of instances. + /// A dictionary mapping to . + /// A containing the message. + public static StringBuilder BuildLoaderExceptionsMessage(this IReadOnlyDictionary loadExceptions) + { + return + loadExceptions.Aggregate( + new StringBuilder("Unable to get all types for some assemblies:").AppendLine(), + (builder, exceptionPair) => + { + var assembly = exceptionPair.Key; + var loadException = exceptionPair.Value; + return BuildLoaderExceptionMessage(builder, assembly, loadException).AppendLine(); + }); + } + + private static StringBuilder BuildLoaderExceptionMessage(StringBuilder builder, Assembly assembly, ReflectionTypeLoadException loadException) + { + var foundTypes = loadException.Types.Count(x => x != null); + var allTypes = loadException.Types.Length; + var loaderMessages = loadException.LoaderExceptions.Select(e => e.Message).Distinct(); + + return loaderMessages.Aggregate( + builder.AppendLine($"- Found {foundTypes} of {allTypes} types from {assembly.FullName}"), + (theBuilder, message) => theBuilder.AppendLine($" - {message}")); + } + + private static IEnumerable SafeGetTypes(this IEnumerable assemblies, Dictionary loadExceptions, Dictionary otherExceptions) + { + return assemblies.SelectMany(assembly => + { + var (types, exception) = assembly.GetTypesAndException(); + if (exception is ReflectionTypeLoadException loadException) + { + loadExceptions.Add(assembly, loadException); + } + else if (exception is not null) { - logger.Error($"Unable to configure services for {assembly.FullName}, see exception for details", ex); + otherExceptions.Add(assembly, exception); } - types = new Type[0]; + return types; + }); + } + + private static (IEnumerable Types, Exception Exception) GetTypesAndException(this Assembly assembly) + { + Exception exception = null; + IEnumerable types; + try + { + types = assembly.GetTypes(); + } + catch (ReflectionTypeLoadException ex) + { + exception = ex; + + // Ensure that DNN obtains all types that were loaded, ignoring the failure(s) + types = ex.Types.Where(x => x != null); + } + catch (Exception ex) + { + exception = ex; + types = Enumerable.Empty(); } - return types; + return (types.OrderBy(type => type.FullName ?? type.Name), exception); } } } diff --git a/DNN Platform/DotNetNuke.DependencyInjection/Extensions/TypesResult.cs b/DNN Platform/DotNetNuke.DependencyInjection/Extensions/TypesResult.cs new file mode 100644 index 00000000000..048bb047491 --- /dev/null +++ b/DNN Platform/DotNetNuke.DependencyInjection/Extensions/TypesResult.cs @@ -0,0 +1,32 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information +namespace DotNetNuke.DependencyInjection.Extensions; + +using System; +using System.Collections.Generic; +using System.Reflection; + +/// The result of a request to get types from assemblies. +public class TypesResult +{ + /// Initializes a new instance of the class. + /// The types. + /// The instances that were occurred while loading the assemblies. + /// The other exceptions that occurred while loading the assemblies. + public TypesResult(IReadOnlyCollection types, IReadOnlyDictionary loadExceptions, IReadOnlyDictionary otherExceptions) + { + this.Types = types; + this.LoadExceptions = loadExceptions; + this.OtherExceptions = otherExceptions; + } + + /// Gets the types. + public IReadOnlyCollection Types { get; } + + /// Gets the instances that were occurred while loading the assemblies. + public IReadOnlyDictionary LoadExceptions { get; } + + /// Gets any other exceptions that occurred while loading the assemblies. + public IReadOnlyDictionary OtherExceptions { get; } +} diff --git a/DNN Platform/DotNetNuke.Instrumentation/DnnLog.cs b/DNN Platform/DotNetNuke.Instrumentation/DnnLog.cs index 6211f968529..81f3f277241 100644 --- a/DNN Platform/DotNetNuke.Instrumentation/DnnLog.cs +++ b/DNN Platform/DotNetNuke.Instrumentation/DnnLog.cs @@ -10,11 +10,12 @@ namespace DotNetNuke.Instrumentation using System.Linq; using System.Web.Compilation; + using DotNetNuke.Internal.SourceGenerators; using log4net.Config; /// Provides access to logging methods. Obsolete, use instead. - [Obsolete("Deprecated in 7.0.1 due to poor performance, use LoggerSource.Instance. Scheduled removal in v11.0.0.")] - public static class DnnLog + [DnnDeprecated(7, 0, 1, "Use LoggerSource.Instance", RemovalVersion = 11)] + public static partial class DnnLog { private const string ConfigFile = "DotNetNuke.log4net.config"; private static readonly DnnLogger Logger = DnnLogger.GetClassLogger(typeof(DnnLog)); diff --git a/DNN Platform/DotNetNuke.Instrumentation/DotNetNuke.Instrumentation.csproj b/DNN Platform/DotNetNuke.Instrumentation/DotNetNuke.Instrumentation.csproj index 8526348520a..54eebe2bdb1 100644 --- a/DNN Platform/DotNetNuke.Instrumentation/DotNetNuke.Instrumentation.csproj +++ b/DNN Platform/DotNetNuke.Instrumentation/DotNetNuke.Instrumentation.csproj @@ -32,7 +32,7 @@ 4 bin\DotNetNuke.Instrumentation.xml 1591, 0649 - 7 + latest true @@ -44,7 +44,7 @@ 4 bin\DotNetNuke.Instrumentation.xml 1591, 0649 - 7 + latest true @@ -81,6 +81,16 @@ + + + {5FE5D021-9C8D-47A6-BD34-F328BA3E709C} + DotNetNuke.Internal.SourceGenerators + + + {6928a9b1-f88a-4581-a132-d3eb38669bb0} + DotNetNuke.Abstractions + + $(MSBuildProjectDirectory)\..\.. diff --git a/DNN Platform/DotNetNuke.Log4net/DotNetNuke.Log4Net.csproj b/DNN Platform/DotNetNuke.Log4net/DotNetNuke.Log4Net.csproj index d77e2278944..cac498482b1 100644 --- a/DNN Platform/DotNetNuke.Log4net/DotNetNuke.Log4Net.csproj +++ b/DNN Platform/DotNetNuke.Log4net/DotNetNuke.Log4Net.csproj @@ -48,8 +48,9 @@ prompt AnyCPU false - 7 + latest bin\DotNetNuke.log4net.xml + true bin\ @@ -61,8 +62,9 @@ prompt AnyCPU false - 7 + latest bin\DotNetNuke.log4net.xml + true diff --git a/DNN Platform/DotNetNuke.Web.Client/ClientResourceManager.cs b/DNN Platform/DotNetNuke.Web.Client/ClientResourceManager.cs index 649a0273a6e..8b5e2cff1f0 100644 --- a/DNN Platform/DotNetNuke.Web.Client/ClientResourceManager.cs +++ b/DNN Platform/DotNetNuke.Web.Client/ClientResourceManager.cs @@ -18,9 +18,10 @@ namespace DotNetNuke.Web.Client.ClientResourceManagement using ClientDependency.Core.CompositeFiles.Providers; using ClientDependency.Core.Config; using DotNetNuke.Instrumentation; + using DotNetNuke.Internal.SourceGenerators; /// Provides the ability to request that client resources (JavaScript and CSS) be loaded on the client browser. - public class ClientResourceManager + public partial class ClientResourceManager { /// The default css provider. internal const string DefaultCssProvider = "DnnPageHeaderProvider"; @@ -440,8 +441,8 @@ public static void RegisterStyleSheet(Page page, string filePath, int priority, } /// This is a utility method that can be called to update the version of the composite files. - [Obsolete("This method is not required anymore. The CRM version is now managed in host settings and site settings.. Scheduled removal in v11.0.0.")] - public static void UpdateVersion() + [DnnDeprecated(8, 0, 1, "This method is not required anymore. The CRM version is now managed in host settings and site settings", RemovalVersion = 10)] + public static partial void UpdateVersion() { } diff --git a/DNN Platform/DotNetNuke.Web.Client/ClientResourceSettings.cs b/DNN Platform/DotNetNuke.Web.Client/ClientResourceSettings.cs index 510aaf3a29d..a34f068ff55 100644 --- a/DNN Platform/DotNetNuke.Web.Client/ClientResourceSettings.cs +++ b/DNN Platform/DotNetNuke.Web.Client/ClientResourceSettings.cs @@ -9,8 +9,10 @@ namespace DotNetNuke.Web.Client using System.Reflection; using System.Web; + using DotNetNuke.Internal.SourceGenerators; + // note: this class is duplicated in ClientDependency.Core.Config.DnnConfiguration, any updates need to be synced between the two. - public class ClientResourceSettings + public partial class ClientResourceSettings { // public keys used to identify the dictionaries stored in the application context public static readonly string HostSettingsDictionaryKey = "HostSettingsDictionary"; @@ -80,8 +82,8 @@ private UpgradeStatus Status } } - [Obsolete("Deprecated in DotNetNuke 9.10.3. Use overload taking portalId. Scheduled removal in v11.0.0.")] - public bool IsOverridingDefaultSettingsEnabled() + [DnnDeprecated(9, 10, 3, "Use overload taking portalId")] + public partial bool IsOverridingDefaultSettingsEnabled() { int? portalId = GetPortalIdThroughReflection(); return this.IsOverridingDefaultSettingsEnabled(portalId); @@ -97,8 +99,8 @@ public bool IsOverridingDefaultSettingsEnabled(int? portalId) return portalVersion.HasValue && overrideDefaultSettings.HasValue && overrideDefaultSettings.Value; } - [Obsolete("Deprecated in DotNetNuke 9.10.3. Use overload taking portalId. Scheduled removal in v11.0.0.")] - public int? GetVersion() + [DnnDeprecated(9, 10, 3, "Use overload taking portalId")] + public partial int? GetVersion() { int? portalId = GetPortalIdThroughReflection(); return this.GetVersion(portalId); diff --git a/DNN Platform/DotNetNuke.Web.Client/DotNetNuke.Web.Client.csproj b/DNN Platform/DotNetNuke.Web.Client/DotNetNuke.Web.Client.csproj index 880bb91f7d2..d688d69ab26 100644 --- a/DNN Platform/DotNetNuke.Web.Client/DotNetNuke.Web.Client.csproj +++ b/DNN Platform/DotNetNuke.Web.Client/DotNetNuke.Web.Client.csproj @@ -32,7 +32,9 @@ 4 bin\DotNetNuke.Web.Client.XML 1591 - 7 + latest + true + SA1600,SA1601,SA1614 pdbonly @@ -43,7 +45,9 @@ 4 bin\DotNetNuke.Web.Client.XML 1591 - 7 + latest + true + SA1600,SA1601,SA1614 @@ -99,6 +103,16 @@ + + + {5FE5D021-9C8D-47A6-BD34-F328BA3E709C} + DotNetNuke.Internal.SourceGenerators + + + {6928a9b1-f88a-4581-a132-d3eb38669bb0} + DotNetNuke.Abstractions + + $(MSBuildProjectDirectory)\..\.. diff --git a/DNN Platform/DotNetNuke.Web.Mvc/Common/TypeHelper.cs b/DNN Platform/DotNetNuke.Web.Mvc/Common/TypeHelper.cs index 306639bcedf..c6735c23b6b 100644 --- a/DNN Platform/DotNetNuke.Web.Mvc/Common/TypeHelper.cs +++ b/DNN Platform/DotNetNuke.Web.Mvc/Common/TypeHelper.cs @@ -2,32 +2,31 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information -namespace DotNetNuke.Web.Mvc.Common -{ - using System.Web.Routing; +namespace DotNetNuke.Web.Mvc.Common +{ + using System.Web.Routing; - public static class TypeHelper - { - /// - /// Given an object of anonymous type, add each property as a key and associated with its value to a dictionary. - /// - /// This helper will cache accessors and types, and is intended when the anonymous object is accessed multiple - /// times throughout the lifetime of the web application. - /// - /// - public static RouteValueDictionary ObjectToDictionary(object value) - { - RouteValueDictionary dictionary = new RouteValueDictionary(); - - if (value != null) - { - foreach (PropertyHelper helper in PropertyHelper.GetProperties(value)) - { - dictionary.Add(helper.Name, helper.GetValue(value)); - } - } - - return dictionary; - } - } -} + public static class TypeHelper + { + /// + /// Given an object of anonymous type, add each property as a key and associated with its value to a dictionary. + /// + /// This helper will cache accessors and types, and is intended when the anonymous object is accessed multiple + /// times throughout the lifetime of the web application. + /// + public static RouteValueDictionary ObjectToDictionary(object value) + { + RouteValueDictionary dictionary = new RouteValueDictionary(); + + if (value != null) + { + foreach (PropertyHelper helper in PropertyHelper.GetProperties(value)) + { + dictionary.Add(helper.Name, helper.GetValue(value)); + } + } + + return dictionary; + } + } +} diff --git a/DNN Platform/DotNetNuke.Web.Mvc/DotNetNuke.Web.Mvc.csproj b/DNN Platform/DotNetNuke.Web.Mvc/DotNetNuke.Web.Mvc.csproj index 88fcb525d17..80c16e43efe 100644 --- a/DNN Platform/DotNetNuke.Web.Mvc/DotNetNuke.Web.Mvc.csproj +++ b/DNN Platform/DotNetNuke.Web.Mvc/DotNetNuke.Web.Mvc.csproj @@ -27,19 +27,27 @@ full false bin\ + bin\DotNetNuke.Web.Mvc.XML DEBUG;TRACE prompt 4 - 7 + 1591 + latest + true + CS0618,SA1600,SA1601,SA1611,SA1612,SA1614,SA1615,SA1618 pdbonly true bin\ + bin\DotNetNuke.Web.Mvc.XML TRACE prompt 4 - 7 + 1591 + latest + true + CS0618,SA1600,SA1601,SA1611,SA1612,SA1614,SA1615,SA1618 @@ -55,8 +63,7 @@ True - ..\..\packages\Newtonsoft.Json.13.0.2\lib\net45\Newtonsoft.Json.dll - True + ..\..\packages\Newtonsoft.Json.13.0.3\lib\net45\Newtonsoft.Json.dll @@ -203,6 +210,10 @@ + + {5fe5d021-9c8d-47a6-bd34-f328ba3e709c} + DotNetNuke.Internal.SourceGenerators + {6928a9b1-f88a-4581-a132-d3eb38669bb0} DotNetNuke.Abstractions diff --git a/DNN Platform/DotNetNuke.Web.Mvc/Extensions/StartupExtensions.cs b/DNN Platform/DotNetNuke.Web.Mvc/Extensions/StartupExtensions.cs index b29da6fe219..0d8ce4495ff 100644 --- a/DNN Platform/DotNetNuke.Web.Mvc/Extensions/StartupExtensions.cs +++ b/DNN Platform/DotNetNuke.Web.Mvc/Extensions/StartupExtensions.cs @@ -3,37 +3,31 @@ // See the LICENSE file in the project root for more information namespace DotNetNuke.Web.Mvc.Extensions { - using System; using System.Linq; using DotNetNuke.DependencyInjection.Extensions; using DotNetNuke.Instrumentation; using DotNetNuke.Web.Mvc.Framework.Controllers; + using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; - /// - /// Adds DNN MVC Controller Specific startup extensions to simplify the - /// Class. - /// + /// Adds DNN MVC Controller Specific startup extensions to simplify the Class. public static class StartupExtensions { private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(StartupExtensions)); - /// - /// Configures all of the 's to be used - /// with the Service Collection for Dependency Injection. - /// - /// - /// Service Collection used to registering services in the container. - /// + /// Configures all of the 's to be used with the Service Collection for Dependency Injection. + /// Service Collection used to registering services in the container. public static void AddMvcControllers(this IServiceCollection services) { - var controllerTypes = AppDomain.CurrentDomain.GetAssemblies() - .SelectMany(x => x.SafeGetTypes(Logger)) - .Where(x => typeof(IDnnController).IsAssignableFrom(x) - && x.IsClass - && !x.IsAbstract); + var allTypes = TypeExtensions.SafeGetTypes(); + allTypes.LogOtherExceptions(Logger); + + var controllerTypes = allTypes.Types + .Where( + type => typeof(IDnnController).IsAssignableFrom(type) && + type is { IsClass: true, IsAbstract: false }); foreach (var controller in controllerTypes) { services.TryAddTransient(controller); diff --git a/DNN Platform/DotNetNuke.Web.Mvc/Framework/ActionFilters/AuthorizeAttributeBase.cs b/DNN Platform/DotNetNuke.Web.Mvc/Framework/ActionFilters/AuthorizeAttributeBase.cs index 4cdda187082..2b989c84846 100644 --- a/DNN Platform/DotNetNuke.Web.Mvc/Framework/ActionFilters/AuthorizeAttributeBase.cs +++ b/DNN Platform/DotNetNuke.Web.Mvc/Framework/ActionFilters/AuthorizeAttributeBase.cs @@ -2,82 +2,80 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information -namespace DotNetNuke.Web.Mvc.Framework.ActionFilters -{ - using System; - using System.Web; - using System.Web.Mvc; +namespace DotNetNuke.Web.Mvc.Framework.ActionFilters +{ + using System; + using System.Web; + using System.Web.Mvc; - using DotNetNuke.Common; + using DotNetNuke.Common; - public abstract class AuthorizeAttributeBase : FilterAttribute, IAuthorizationFilter - { - public static bool IsAnonymousAttributePresent(AuthorizationContext filterContext) - { - return filterContext.ActionDescriptor.IsDefined(typeof(AllowAnonymousAttribute), inherit: true) - || filterContext.ActionDescriptor.ControllerDescriptor.IsDefined(typeof(AllowAnonymousAttribute), inherit: true); + public abstract class AuthorizeAttributeBase : FilterAttribute, IAuthorizationFilter + { + public static bool IsAnonymousAttributePresent(AuthorizationContext filterContext) + { + return filterContext.ActionDescriptor.IsDefined(typeof(AllowAnonymousAttribute), inherit: true) + || filterContext.ActionDescriptor.ControllerDescriptor.IsDefined(typeof(AllowAnonymousAttribute), inherit: true); } /// - public virtual void OnAuthorization(AuthorizationContext filterContext) - { - Requires.NotNull("filterContext", filterContext); - - if (this.SkipAuthorization(filterContext)) - { - return; - } - - if (this.AuthorizeCore(filterContext.HttpContext)) - { - this.HandleAuthorizedRequest(filterContext); - } - else - { - this.HandleUnauthorizedRequest(filterContext); - } - } - - protected virtual bool AuthorizeCore(HttpContextBase httpContext) - { - return true; - } - - protected virtual void HandleAuthorizedRequest(AuthorizationContext filterContext) - { - HttpCachePolicyBase cachePolicy = filterContext.HttpContext.Response.Cache; - cachePolicy.SetProxyMaxAge(new TimeSpan(0)); - cachePolicy.AddValidationCallback(this.CacheValidateHandler, null /* data */); - } - - protected virtual void HandleUnauthorizedRequest(AuthorizationContext filterContext) - { - const string failureMessage = "Authorization has been denied for this request."; - var authFilterContext = new AuthFilterContext(filterContext, failureMessage); - authFilterContext.HandleUnauthorizedRequest(); - - // filterContext.HttpContext.Response.Redirect(Globals.AccessDeniedURL()); - } - - protected virtual HttpValidationStatus OnCacheAuthorization(HttpContextBase httpContext) - { - Requires.NotNull("httpContext", httpContext); - - bool isAuthorized = this.AuthorizeCore(httpContext); - return isAuthorized ? HttpValidationStatus.Valid : HttpValidationStatus.IgnoreThisRequest; - } - - /// Skips this authorization step if anonymous attribute is applied, override if auth should never be skipped, or other conditions are required. - /// - /// - protected virtual bool SkipAuthorization(AuthorizationContext filterContext) - { - return IsAnonymousAttributePresent(filterContext); - } - - private void CacheValidateHandler(HttpContext context, object data, ref HttpValidationStatus validationStatus) - { - validationStatus = this.OnCacheAuthorization(new HttpContextWrapper(context)); - } - } -} + public virtual void OnAuthorization(AuthorizationContext filterContext) + { + Requires.NotNull("filterContext", filterContext); + + if (this.SkipAuthorization(filterContext)) + { + return; + } + + if (this.AuthorizeCore(filterContext.HttpContext)) + { + this.HandleAuthorizedRequest(filterContext); + } + else + { + this.HandleUnauthorizedRequest(filterContext); + } + } + + protected virtual bool AuthorizeCore(HttpContextBase httpContext) + { + return true; + } + + protected virtual void HandleAuthorizedRequest(AuthorizationContext filterContext) + { + HttpCachePolicyBase cachePolicy = filterContext.HttpContext.Response.Cache; + cachePolicy.SetProxyMaxAge(new TimeSpan(0)); + cachePolicy.AddValidationCallback(this.CacheValidateHandler, null /* data */); + } + + protected virtual void HandleUnauthorizedRequest(AuthorizationContext filterContext) + { + const string failureMessage = "Authorization has been denied for this request."; + var authFilterContext = new AuthFilterContext(filterContext, failureMessage); + authFilterContext.HandleUnauthorizedRequest(); + + // filterContext.HttpContext.Response.Redirect(Globals.AccessDeniedURL()); + } + + protected virtual HttpValidationStatus OnCacheAuthorization(HttpContextBase httpContext) + { + Requires.NotNull("httpContext", httpContext); + + bool isAuthorized = this.AuthorizeCore(httpContext); + return isAuthorized ? HttpValidationStatus.Valid : HttpValidationStatus.IgnoreThisRequest; + } + + /// Skips this authorization step if anonymous attribute is applied, override if auth should never be skipped, or other conditions are required. + protected virtual bool SkipAuthorization(AuthorizationContext filterContext) + { + return IsAnonymousAttributePresent(filterContext); + } + + private void CacheValidateHandler(HttpContext context, object data, ref HttpValidationStatus validationStatus) + { + validationStatus = this.OnCacheAuthorization(new HttpContextWrapper(context)); + } + } +} diff --git a/DNN Platform/DotNetNuke.Web.Mvc/Routing/PortalAliasMvcRouteManager.cs b/DNN Platform/DotNetNuke.Web.Mvc/Routing/PortalAliasMvcRouteManager.cs index d1e5333ba17..b37890663a8 100644 --- a/DNN Platform/DotNetNuke.Web.Mvc/Routing/PortalAliasMvcRouteManager.cs +++ b/DNN Platform/DotNetNuke.Web.Mvc/Routing/PortalAliasMvcRouteManager.cs @@ -1,177 +1,178 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information -namespace DotNetNuke.Web.Mvc.Routing -{ - using System; - using System.Collections.Generic; - using System.Globalization; - using System.Linq; - using System.Web.Routing; - - using DotNetNuke.Abstractions.Portals; - using DotNetNuke.Common; - using DotNetNuke.Common.Internal; - using DotNetNuke.Entities.Portals; - - internal class PortalAliasMvcRouteManager : IPortalAliasMvcRouteManager - { +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information +namespace DotNetNuke.Web.Mvc.Routing +{ + using System; + using System.Collections.Generic; + using System.Globalization; + using System.Linq; + using System.Web.Routing; + + using DotNetNuke.Abstractions.Portals; + using DotNetNuke.Common; + using DotNetNuke.Common.Internal; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Internal.SourceGenerators; + + internal partial class PortalAliasMvcRouteManager : IPortalAliasMvcRouteManager + { private List prefixCounts; /// - public string GetRouteName(string moduleFolderName, string routeName, int count) - { - Requires.NotNullOrEmpty("moduleFolderName", moduleFolderName); - Requires.NotNegative("count", count); - - return moduleFolderName + "-" + routeName + "-" + count.ToString(CultureInfo.InvariantCulture); + public string GetRouteName(string moduleFolderName, string routeName, int count) + { + Requires.NotNullOrEmpty("moduleFolderName", moduleFolderName); + Requires.NotNegative("count", count); + + return moduleFolderName + "-" + routeName + "-" + count.ToString(CultureInfo.InvariantCulture); } - /// - [Obsolete("Deprecated in 9.10.0. Scheduled for removal in v11.0.0, use overload taking DotNetNuke.Abstractions.Portals.IPortalAliasInfo instead.")] - public string GetRouteName(string moduleFolderName, string routeName, PortalAliasInfo portalAlias) - { - return this.GetRouteName(moduleFolderName, routeName, (IPortalAliasInfo)portalAlias); - } - - public string GetRouteName(string moduleFolderName, string routeName, IPortalAliasInfo portalAlias) - { - var alias = portalAlias.HttpAlias; - string appPath = TestableGlobals.Instance.ApplicationPath; - if (!string.IsNullOrEmpty(appPath)) - { - int i = alias.IndexOf(appPath, StringComparison.OrdinalIgnoreCase); - if (i > 0) - { - alias = alias.Remove(i, appPath.Length); - } - } - - return this.GetRouteName(moduleFolderName, routeName, CalcAliasPrefixCount(alias)); + /// + [DnnDeprecated(9, 10, 0, "Use overload taking DotNetNuke.Abstractions.Portals.IPortalAliasInfo instead")] + public partial string GetRouteName(string moduleFolderName, string routeName, PortalAliasInfo portalAlias) + { + return this.GetRouteName(moduleFolderName, routeName, (IPortalAliasInfo)portalAlias); } - /// - [Obsolete("Deprecated in 9.10.0. Scheduled for removal in v11.0.0, use overload taking DotNetNuke.Abstractions.Portals.IPortalAliasInfo instead.")] - public RouteValueDictionary GetAllRouteValues(PortalAliasInfo portalAliasInfo, object routeValues) - { - return this.GetAllRouteValues((IPortalAliasInfo)portalAliasInfo, routeValues); - } - - public RouteValueDictionary GetAllRouteValues(IPortalAliasInfo portalAliasInfo, object routeValues) - { - var allRouteValues = new RouteValueDictionary(routeValues); - - var segments = portalAliasInfo.HttpAlias.Split('/'); - - if (segments.Length <= 1) - { - return allRouteValues; - } - - for (var i = 1; i < segments.Length; i++) - { - var key = "prefix" + (i - 1).ToString(CultureInfo.InvariantCulture); - var value = segments[i]; - allRouteValues.Add(key, value); - } - - return allRouteValues; + public string GetRouteName(string moduleFolderName, string routeName, IPortalAliasInfo portalAlias) + { + var alias = portalAlias.HttpAlias; + string appPath = TestableGlobals.Instance.ApplicationPath; + if (!string.IsNullOrEmpty(appPath)) + { + int i = alias.IndexOf(appPath, StringComparison.OrdinalIgnoreCase); + if (i > 0) + { + alias = alias.Remove(i, appPath.Length); + } + } + + return this.GetRouteName(moduleFolderName, routeName, CalcAliasPrefixCount(alias)); + } + + /// + [DnnDeprecated(9, 10, 0, "Use overload taking DotNetNuke.Abstractions.Portals.IPortalAliasInfo instead")] + public partial RouteValueDictionary GetAllRouteValues(PortalAliasInfo portalAliasInfo, object routeValues) + { + return this.GetAllRouteValues((IPortalAliasInfo)portalAliasInfo, routeValues); + } + + public RouteValueDictionary GetAllRouteValues(IPortalAliasInfo portalAliasInfo, object routeValues) + { + var allRouteValues = new RouteValueDictionary(routeValues); + + var segments = portalAliasInfo.HttpAlias.Split('/'); + + if (segments.Length <= 1) + { + return allRouteValues; + } + + for (var i = 1; i < segments.Length; i++) + { + var key = "prefix" + (i - 1).ToString(CultureInfo.InvariantCulture); + var value = segments[i]; + allRouteValues.Add(key, value); + } + + return allRouteValues; } /// - public string GetRouteUrl(string moduleFolderName, string url, int count) - { - Requires.NotNegative("count", count); - Requires.NotNullOrEmpty("moduleFolderName", moduleFolderName); - - return $"{GeneratePrefixString(count)}DesktopModules/MVC/{moduleFolderName}/{url}"; + public string GetRouteUrl(string moduleFolderName, string url, int count) + { + Requires.NotNegative("count", count); + Requires.NotNullOrEmpty("moduleFolderName", moduleFolderName); + + return $"{GeneratePrefixString(count)}DesktopModules/MVC/{moduleFolderName}/{url}"; } /// - public void ClearCachedData() - { - this.prefixCounts = null; + public void ClearCachedData() + { + this.prefixCounts = null; } /// - public IEnumerable GetRoutePrefixCounts() - { - if (this.prefixCounts != null) - { - return this.prefixCounts; - } - - // prefixCounts are required for each route that is mapped but they only change - // when a new portal is added so cache them until that time - var portals = PortalController.Instance.GetPortals(); - var segmentCounts1 = new List(); - - foreach ( - var count in - portals.Cast() - .Select( - portal => - PortalAliasController.Instance.GetPortalAliasesByPortalId(portal.PortalId) - .Cast() - .Select(x => x.HttpAlias)) - .Select(this.StripApplicationPath) - .SelectMany( - aliases => - aliases.Select(CalcAliasPrefixCount).Where(count => !segmentCounts1.Contains(count)))) - { - segmentCounts1.Add(count); - } - - IEnumerable segmentCounts = segmentCounts1; - this.prefixCounts = segmentCounts.OrderByDescending(x => x).ToList(); - - return this.prefixCounts; - } - - private static string GeneratePrefixString(int count) - { - if (count == 0) - { - return string.Empty; - } - - var prefix = string.Empty; - - for (var i = count - 1; i >= 0; i--) - { - prefix = "{prefix" + i + "}/" + prefix; - } - - return prefix; - } - - private static int CalcAliasPrefixCount(string alias) - { - return alias.Count(c => c == '/'); - } - - private static IEnumerable StripApplicationPathIterable(IEnumerable aliases, string appPath) - { - foreach (var alias in aliases) - { - var i = alias.IndexOf(appPath, StringComparison.OrdinalIgnoreCase); - - if (i > 0) - { - yield return alias.Remove(i, appPath.Length); - } - else - { - yield return alias; - } - } - } - - private IEnumerable StripApplicationPath(IEnumerable aliases) - { - var appPath = TestableGlobals.Instance.ApplicationPath; - - return string.IsNullOrEmpty(appPath) ? aliases : StripApplicationPathIterable(aliases, appPath); - } - } -} + public IEnumerable GetRoutePrefixCounts() + { + if (this.prefixCounts != null) + { + return this.prefixCounts; + } + + // prefixCounts are required for each route that is mapped but they only change + // when a new portal is added so cache them until that time + var portals = PortalController.Instance.GetPortals(); + var segmentCounts1 = new List(); + + foreach ( + var count in + portals.Cast() + .Select( + portal => + PortalAliasController.Instance.GetPortalAliasesByPortalId(portal.PortalId) + .Cast() + .Select(x => x.HttpAlias)) + .Select(this.StripApplicationPath) + .SelectMany( + aliases => + aliases.Select(CalcAliasPrefixCount).Where(count => !segmentCounts1.Contains(count)))) + { + segmentCounts1.Add(count); + } + + IEnumerable segmentCounts = segmentCounts1; + this.prefixCounts = segmentCounts.OrderByDescending(x => x).ToList(); + + return this.prefixCounts; + } + + private static string GeneratePrefixString(int count) + { + if (count == 0) + { + return string.Empty; + } + + var prefix = string.Empty; + + for (var i = count - 1; i >= 0; i--) + { + prefix = "{prefix" + i + "}/" + prefix; + } + + return prefix; + } + + private static int CalcAliasPrefixCount(string alias) + { + return alias.Count(c => c == '/'); + } + + private static IEnumerable StripApplicationPathIterable(IEnumerable aliases, string appPath) + { + foreach (var alias in aliases) + { + var i = alias.IndexOf(appPath, StringComparison.OrdinalIgnoreCase); + + if (i > 0) + { + yield return alias.Remove(i, appPath.Length); + } + else + { + yield return alias; + } + } + } + + private IEnumerable StripApplicationPath(IEnumerable aliases) + { + var appPath = TestableGlobals.Instance.ApplicationPath; + + return string.IsNullOrEmpty(appPath) ? aliases : StripApplicationPathIterable(aliases, appPath); + } + } +} diff --git a/DNN Platform/DotNetNuke.Web.Mvc/packages.config b/DNN Platform/DotNetNuke.Web.Mvc/packages.config index ad616f3b869..c42bd9d330d 100644 --- a/DNN Platform/DotNetNuke.Web.Mvc/packages.config +++ b/DNN Platform/DotNetNuke.Web.Mvc/packages.config @@ -13,6 +13,6 @@ - + \ No newline at end of file diff --git a/DNN Platform/DotNetNuke.Web.Razor/DotNetNuke.Web.Razor.csproj b/DNN Platform/DotNetNuke.Web.Razor/DotNetNuke.Web.Razor.csproj index ee3c5f8665b..69872116ee2 100644 --- a/DNN Platform/DotNetNuke.Web.Razor/DotNetNuke.Web.Razor.csproj +++ b/DNN Platform/DotNetNuke.Web.Razor/DotNetNuke.Web.Razor.csproj @@ -7,6 +7,7 @@ true + latest Debug @@ -35,7 +36,9 @@ bin\DotNetNuke.Web.Razor.XML 4 1591 - 7 + latest + true + CS0618,CS0809,SA1600,SA1601 pdbonly @@ -44,7 +47,9 @@ bin\ bin\DotNetNuke.Web.Razor.XML 1591 - 7 + latest + true + CS0618,CS0809,SA1600,SA1601 On @@ -132,6 +137,10 @@ + + {5fe5d021-9c8d-47a6-bd34-f328ba3e709c} + DotNetNuke.Internal.SourceGenerators + {6928a9b1-f88a-4581-a132-d3eb38669bb0} DotNetNuke.Abstractions diff --git a/DNN Platform/DotNetNuke.Web.Razor/DotNetNukeWebPage.cs b/DNN Platform/DotNetNuke.Web.Razor/DotNetNukeWebPage.cs index efc21068ecd..09ba73c4416 100644 --- a/DNN Platform/DotNetNuke.Web.Razor/DotNetNukeWebPage.cs +++ b/DNN Platform/DotNetNuke.Web.Razor/DotNetNukeWebPage.cs @@ -1,38 +1,34 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information - namespace DotNetNuke.Web.Razor { using System; using System.Web.WebPages; + using DotNetNuke.Internal.SourceGenerators; using DotNetNuke.Web.Razor.Helpers; - [Obsolete("Deprecated in 9.3.2, will be removed in 11.0.0, use Razor Pages instead")] - public abstract class DotNetNukeWebPage : WebPageBase + [DnnDeprecated(9, 3, 2, "Use Razor Pages instead")] + public abstract partial class DotNetNukeWebPage : WebPageBase { private dynamic model; - [Obsolete("Deprecated in 9.3.2, will be removed in 11.0.0, use Razor Pages instead")] public dynamic Model { get { return this.model ?? (this.model = this.PageContext.Model); } set { this.model = value; } } - [Obsolete("Deprecated in 9.3.2, will be removed in 11.0.0, use Razor Pages instead")] protected internal DnnHelper Dnn { get; internal set; } - [Obsolete("Deprecated in 9.3.2, will be removed in 11.0.0, use Razor Pages instead")] protected internal HtmlHelper Html { get; internal set; } - [Obsolete("Deprecated in 9.3.2, will be removed in 11.0.0, use Razor Pages instead")] protected internal UrlHelper Url { get; internal set; } /// - [Obsolete("Deprecated in 9.3.2, will be removed in 11.0.0, use Razor Pages instead")] - protected override void ConfigurePage(WebPageBase parentPage) + [DnnDeprecated(9, 3, 2, "Use Razor Pages instead")] + protected override partial void ConfigurePage(WebPageBase parentPage) { base.ConfigurePage(parentPage); diff --git a/DNN Platform/DotNetNuke.Web.Razor/DotNetNukeWebPage{TModel}.cs b/DNN Platform/DotNetNuke.Web.Razor/DotNetNukeWebPage{TModel}.cs index 0145afdc935..298913ce678 100644 --- a/DNN Platform/DotNetNuke.Web.Razor/DotNetNukeWebPage{TModel}.cs +++ b/DNN Platform/DotNetNuke.Web.Razor/DotNetNukeWebPage{TModel}.cs @@ -7,10 +7,12 @@ namespace DotNetNuke.Web.Razor using System; using DotNetNuke.Common; + using DotNetNuke.Internal.SourceGenerators; + using Microsoft.Extensions.DependencyInjection; - [Obsolete("Deprecated in 9.3.2, will be removed in 11.0.0, use Razor Pages instead")] - public abstract class DotNetNukeWebPage : DotNetNukeWebPage + [DnnDeprecated(9, 3, 2, "Use Razor Pages instead")] + public abstract partial class DotNetNukeWebPage : DotNetNukeWebPage where TModel : class { private TModel model; @@ -21,7 +23,6 @@ public DotNetNukeWebPage() this.Model = model ?? Activator.CreateInstance(); } - [Obsolete("Deprecated in 9.3.2, will be removed in 11.0.0, use Razor Pages instead")] public new TModel Model { get { return this.PageContext?.Model as TModel ?? this.model; } diff --git a/DNN Platform/DotNetNuke.Web.Razor/Helpers/DnnHelper.cs b/DNN Platform/DotNetNuke.Web.Razor/Helpers/DnnHelper.cs index 3d196f14068..330caf9f161 100644 --- a/DNN Platform/DotNetNuke.Web.Razor/Helpers/DnnHelper.cs +++ b/DNN Platform/DotNetNuke.Web.Razor/Helpers/DnnHelper.cs @@ -1,61 +1,55 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information -namespace DotNetNuke.Web.Razor.Helpers -{ - using System; +namespace DotNetNuke.Web.Razor.Helpers +{ + using DotNetNuke.Entities.Modules; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Tabs; + using DotNetNuke.Entities.Users; + using DotNetNuke.Internal.SourceGenerators; + using DotNetNuke.UI.Modules; - using DotNetNuke.Entities.Modules; - using DotNetNuke.Entities.Portals; - using DotNetNuke.Entities.Tabs; - using DotNetNuke.Entities.Users; - using DotNetNuke.UI.Modules; + [DnnDeprecated(9, 3, 2, "Use Razor Pages instead")] + public partial class DnnHelper + { + private readonly ModuleInstanceContext context; - [Obsolete("Deprecated in 9.3.2, will be removed in 11.0.0, use Razor Pages instead")] - public class DnnHelper - { - private readonly ModuleInstanceContext context; - - [Obsolete("Deprecated in 9.3.2, will be removed in 11.0.0, use Razor Pages instead")] - public DnnHelper(ModuleInstanceContext context) - { - this.context = context; - } - - [Obsolete("Deprecated in 9.3.2, will be removed in 11.0.0, use Razor Pages instead")] - public ModuleInfo Module - { - get - { - return this.context.Configuration; - } - } - - [Obsolete("Deprecated in 9.3.2, will be removed in 11.0.0, use Razor Pages instead")] - public TabInfo Tab - { - get - { - return this.context.PortalSettings.ActiveTab; - } - } - - [Obsolete("Deprecated in 9.3.2, will be removed in 11.0.0, use Razor Pages instead")] - public PortalSettings Portal - { - get - { - return this.context.PortalSettings; - } - } - - [Obsolete("Deprecated in 9.3.2, will be removed in 11.0.0, use Razor Pages instead")] - public UserInfo User - { - get - { - return this.context.PortalSettings.UserInfo; - } - } - } -} + public DnnHelper(ModuleInstanceContext context) + { + this.context = context; + } + + public ModuleInfo Module + { + get + { + return this.context.Configuration; + } + } + + public TabInfo Tab + { + get + { + return this.context.PortalSettings.ActiveTab; + } + } + + public PortalSettings Portal + { + get + { + return this.context.PortalSettings; + } + } + + public UserInfo User + { + get + { + return this.context.PortalSettings.UserInfo; + } + } + } +} diff --git a/DNN Platform/DotNetNuke.Web.Razor/Helpers/HtmlHelper.cs b/DNN Platform/DotNetNuke.Web.Razor/Helpers/HtmlHelper.cs index ed2ceed405d..fc935a3a3f7 100644 --- a/DNN Platform/DotNetNuke.Web.Razor/Helpers/HtmlHelper.cs +++ b/DNN Platform/DotNetNuke.Web.Razor/Helpers/HtmlHelper.cs @@ -1,43 +1,43 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information -namespace DotNetNuke.Web.Razor.Helpers -{ - using System; +namespace DotNetNuke.Web.Razor.Helpers +{ + using System; using System.Web; - using DotNetNuke.Services.Localization; - using DotNetNuke.UI.Modules; + using DotNetNuke.Internal.SourceGenerators; + using DotNetNuke.Services.Localization; + using DotNetNuke.UI.Modules; - [Obsolete("Deprecated in 9.3.2, will be removed in 11.0.0, use Razor Pages instead")] - public class HtmlHelper - { - private readonly string resourceFile; - private ModuleInstanceContext context; - - [Obsolete("Deprecated in 9.3.2, will be removed in 11.0.0, use Razor Pages instead")] - public HtmlHelper(ModuleInstanceContext context, string resourcefile) - { - this.context = context; - this.resourceFile = resourcefile; - } - - [Obsolete("Deprecated in 9.3.2, will be removed in 11.0.0, use Razor Pages instead")] - public object GetLocalizedString(string key) - { - return Localization.GetString(key, this.resourceFile); - } - - [Obsolete("Deprecated in 9.3.2, will be removed in 11.0.0, use Razor Pages instead")] - public object GetLocalizedString(string key, string culture) - { - return Localization.GetString(key, this.resourceFile, culture); - } - - [Obsolete("Deprecated in 9.3.2, will be removed in 11.0.0, use Razor Pages instead")] - public HtmlString Raw(string text) - { - return new HtmlString(text); - } - } -} + [DnnDeprecated(9, 3, 2, "Use Razor Pages instead")] + public partial class HtmlHelper + { + private readonly string resourceFile; + private ModuleInstanceContext context; + + public HtmlHelper(ModuleInstanceContext context, string resourcefile) + { + this.context = context; + this.resourceFile = resourcefile; + } + + [DnnDeprecated(9, 3, 2, "Use Razor Pages instead")] + public partial object GetLocalizedString(string key) + { + return Localization.GetString(key, this.resourceFile); + } + + [DnnDeprecated(9, 3, 2, "Use Razor Pages instead")] + public partial object GetLocalizedString(string key, string culture) + { + return Localization.GetString(key, this.resourceFile, culture); + } + + [DnnDeprecated(9, 3, 2, "Use Razor Pages instead")] + public partial HtmlString Raw(string text) + { + return new HtmlString(text); + } + } +} diff --git a/DNN Platform/DotNetNuke.Web.Razor/Helpers/UrlHelper.cs b/DNN Platform/DotNetNuke.Web.Razor/Helpers/UrlHelper.cs index 9ee1de03414..1eb11a450e5 100644 --- a/DNN Platform/DotNetNuke.Web.Razor/Helpers/UrlHelper.cs +++ b/DNN Platform/DotNetNuke.Web.Razor/Helpers/UrlHelper.cs @@ -1,41 +1,41 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information -namespace DotNetNuke.Web.Razor.Helpers -{ - using System; +namespace DotNetNuke.Web.Razor.Helpers +{ + using System; - using DotNetNuke.Abstractions; - using DotNetNuke.Common; - using DotNetNuke.UI.Modules; + using DotNetNuke.Abstractions; + using DotNetNuke.Common; + using DotNetNuke.Internal.SourceGenerators; + using DotNetNuke.UI.Modules; using Microsoft.Extensions.DependencyInjection; - [Obsolete("Deprecated in 9.3.2, will be removed in 11.0.0, use Razor Pages instead")] - public class UrlHelper - { + [DnnDeprecated(9, 3, 2, "Use Razor Pages instead")] + public partial class UrlHelper + { private readonly ModuleInstanceContext context; /// Initializes a new instance of the class. /// The module context. - [Obsolete("Deprecated in 9.3.2, will be removed in 11.0.0, use Razor Pages instead")] - public UrlHelper(ModuleInstanceContext context) - { - this.context = context; - this.NavigationManager = Globals.DependencyProvider.GetRequiredService(); - } - - protected INavigationManager NavigationManager { get; } - - [Obsolete("Deprecated in 9.3.2, will be removed in 11.0.0, use Razor Pages instead")] - public string NavigateToControl() - { - return this.NavigationManager.NavigateURL(this.context.TabId); - } - - [Obsolete("Deprecated in 9.3.2, will be removed in 11.0.0, use Razor Pages instead")] - public string NavigateToControl(string controlKey) - { - return this.NavigationManager.NavigateURL(this.context.TabId, controlKey, "mid=" + this.context.ModuleId); - } - } -} + public UrlHelper(ModuleInstanceContext context) + { + this.context = context; + this.NavigationManager = Globals.DependencyProvider.GetRequiredService(); + } + + protected INavigationManager NavigationManager { get; } + + [DnnDeprecated(9, 3, 2, "Use Razor Pages instead")] + public partial string NavigateToControl() + { + return this.NavigationManager.NavigateURL(this.context.TabId); + } + + [DnnDeprecated(9, 3, 2, "Use Razor Pages instead")] + public partial string NavigateToControl(string controlKey) + { + return this.NavigationManager.NavigateURL(this.context.TabId, controlKey, "mid=" + this.context.ModuleId); + } + } +} diff --git a/DNN Platform/DotNetNuke.Web.Razor/RazorEngine.cs b/DNN Platform/DotNetNuke.Web.Razor/RazorEngine.cs index 2465b4d994a..b7d45a85db2 100644 --- a/DNN Platform/DotNetNuke.Web.Razor/RazorEngine.cs +++ b/DNN Platform/DotNetNuke.Web.Razor/RazorEngine.cs @@ -11,15 +11,15 @@ namespace DotNetNuke.Web.Razor using System.Web.Compilation; using System.Web.WebPages; + using DotNetNuke.Internal.SourceGenerators; using DotNetNuke.Services.Exceptions; using DotNetNuke.Services.Localization; using DotNetNuke.UI.Modules; using DotNetNuke.Web.Razor.Helpers; - [Obsolete("Deprecated in 9.3.2, will be removed in 11.0.0, use Razor Pages instead")] - public class RazorEngine + [DnnDeprecated(9, 3, 2, "Use Razor Pages instead")] + public partial class RazorEngine { - [Obsolete("Deprecated in 9.3.2, will be removed in 11.0.0, use Razor Pages instead")] public RazorEngine(string razorScriptFile, ModuleInstanceContext moduleContext, string localResourceFile) { this.RazorScriptFile = razorScriptFile; @@ -44,26 +44,21 @@ public RazorEngine(string razorScriptFile, ModuleInstanceContext moduleContext, } } - [Obsolete("Deprecated in 9.3.2, will be removed in 11.0.0, use Razor Pages instead")] public DotNetNukeWebPage Webpage { get; set; } - [Obsolete("Deprecated in 9.3.2, will be removed in 11.0.0, use Razor Pages instead")] protected HttpContextBase HttpContext { get { return new HttpContextWrapper(System.Web.HttpContext.Current); } } - [Obsolete("Deprecated in 9.3.2, will be removed in 11.0.0, use Razor Pages instead")] protected string RazorScriptFile { get; set; } - [Obsolete("Deprecated in 9.3.2, will be removed in 11.0.0, use Razor Pages instead")] protected ModuleInstanceContext ModuleContext { get; set; } - [Obsolete("Deprecated in 9.3.2, will be removed in 11.0.0, use Razor Pages instead")] protected string LocalResourceFile { get; set; } - [Obsolete("Deprecated in 9.3.2, will be removed in 11.0.0, use Razor Pages instead")] - public Type RequestedModelType() + [DnnDeprecated(9, 3, 2, "Use Razor Pages instead")] + public partial Type RequestedModelType() { if (this.Webpage != null) { @@ -77,8 +72,8 @@ public Type RequestedModelType() return null; } - [Obsolete("Deprecated in 9.3.2, will be removed in 11.0.0, use Razor Pages instead")] - public void Render(TextWriter writer, T model) + [DnnDeprecated(9, 3, 2, "Use Razor Pages instead")] + public partial void Render(TextWriter writer, T model) { try { @@ -90,8 +85,8 @@ public void Render(TextWriter writer, T model) } } - [Obsolete("Deprecated in 9.3.2, will be removed in 11.0.0, use Razor Pages instead")] - public void Render(TextWriter writer) + [DnnDeprecated(9, 3, 2, "Use Razor Pages instead")] + public partial void Render(TextWriter writer) { try { @@ -103,8 +98,8 @@ public void Render(TextWriter writer) } } - [Obsolete("Deprecated in 9.3.2, will be removed in 11.0.0, use Razor Pages instead")] - public void Render(TextWriter writer, WebPageContext context) + [DnnDeprecated(9, 3, 2, "Use Razor Pages instead")] + public partial void Render(TextWriter writer, WebPageContext context) { try { diff --git a/DNN Platform/DotNetNuke.Web.Razor/RazorHostControl.cs b/DNN Platform/DotNetNuke.Web.Razor/RazorHostControl.cs index e106df635d3..70f186094fb 100644 --- a/DNN Platform/DotNetNuke.Web.Razor/RazorHostControl.cs +++ b/DNN Platform/DotNetNuke.Web.Razor/RazorHostControl.cs @@ -1,78 +1,76 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information -namespace DotNetNuke.Web.Razor -{ - using System; - using System.IO; - using System.Web; - using System.Web.UI; +namespace DotNetNuke.Web.Razor +{ + using System; + using System.IO; + using System.Web; + using System.Web.UI; - using DotNetNuke.Entities.Modules; - using DotNetNuke.Entities.Modules.Actions; + using DotNetNuke.Entities.Modules; + using DotNetNuke.Entities.Modules.Actions; + using DotNetNuke.Internal.SourceGenerators; using DotNetNuke.UI.Modules; - [Obsolete("Deprecated in 9.3.2, will be removed in 11.0.0, use Razor Pages instead")] - public class RazorHostControl : ModuleControlBase, IActionable - { - private readonly string razorScriptFile; - + [DnnDeprecated(9, 3, 2, "Use Razor Pages instead")] + public partial class RazorHostControl : ModuleControlBase, IActionable + { + private readonly string razorScriptFile; + private RazorEngine engine; /// Initializes a new instance of the class. /// The path to the Razor script file. - [Obsolete("Deprecated in 9.3.2, will be removed in 11.0.0, use Razor Pages instead")] - public RazorHostControl(string scriptFile) - { - this.razorScriptFile = scriptFile; + public RazorHostControl(string scriptFile) + { + this.razorScriptFile = scriptFile; } /// - [Obsolete("Deprecated in 9.3.2, will be removed in 11.0.0, use Razor Pages instead")] - public ModuleActionCollection ModuleActions - { - get - { - if (this.Engine.Webpage is IActionable) - { - return (this.Engine.Webpage as IActionable).ModuleActions; - } - - return new ModuleActionCollection(); - } - } - - [Obsolete("Deprecated in 9.3.2, will be removed in 11.0.0, use Razor Pages instead")] - protected virtual string RazorScriptFile - { - get { return this.razorScriptFile; } - } - - private RazorEngine Engine - { - get - { - if (this.engine == null) - { - this.engine = new RazorEngine(this.RazorScriptFile, this.ModuleContext, this.LocalResourceFile); - } - - return this.engine; - } + public ModuleActionCollection ModuleActions + { + get + { + if (this.Engine.Webpage is IActionable) + { + return (this.Engine.Webpage as IActionable).ModuleActions; + } + + return new ModuleActionCollection(); + } + } + + protected virtual string RazorScriptFile + { + get { return this.razorScriptFile; } + } + + private RazorEngine Engine + { + get + { + if (this.engine == null) + { + this.engine = new RazorEngine(this.RazorScriptFile, this.ModuleContext, this.LocalResourceFile); + } + + return this.engine; + } } /// - [Obsolete("Deprecated in 9.3.2, will be removed in 11.0.0, use Razor Pages instead")] - protected override void OnPreRender(EventArgs e) - { - base.OnPreRender(e); - - if (!string.IsNullOrEmpty(this.RazorScriptFile)) - { - var writer = new StringWriter(); - this.Engine.Render(writer); - this.Controls.Add(new LiteralControl(HttpUtility.HtmlDecode(writer.ToString()))); - } - } - } -} + [DnnDeprecated(9, 3, 2, "Use Razor Pages instead")] + protected override partial void OnPreRender(EventArgs e) + { + base.OnPreRender(e); + + if (!string.IsNullOrEmpty(this.RazorScriptFile)) + { + var writer = new StringWriter(); + this.Engine.Render(writer); + this.Controls.Add(new LiteralControl(HttpUtility.HtmlDecode(writer.ToString()))); + } + } + } +} diff --git a/DNN Platform/DotNetNuke.Web.Razor/RazorModuleBase.cs b/DNN Platform/DotNetNuke.Web.Razor/RazorModuleBase.cs index dcb989e3920..773157ab5e4 100644 --- a/DNN Platform/DotNetNuke.Web.Razor/RazorModuleBase.cs +++ b/DNN Platform/DotNetNuke.Web.Razor/RazorModuleBase.cs @@ -1,63 +1,63 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information -namespace DotNetNuke.Web.Razor -{ - using System; - using System.IO; - using System.Web.UI; +namespace DotNetNuke.Web.Razor +{ + using System; + using System.IO; + using System.Web.UI; - using DotNetNuke.Services.Exceptions; + using DotNetNuke.Internal.SourceGenerators; + using DotNetNuke.Services.Exceptions; using DotNetNuke.UI.Modules; - [Obsolete("Deprecated in 9.3.2, will be removed in 11.0.0, use Razor Pages instead")] - public class RazorModuleBase : ModuleUserControlBase - { - [Obsolete("Deprecated in 9.3.2, will be removed in 11.0.0, use Razor Pages instead")] - protected virtual string RazorScriptFile - { - get - { - var scriptFolder = this.AppRelativeTemplateSourceDirectory; - var fileRoot = Path.GetFileNameWithoutExtension(this.AppRelativeVirtualPath); - var scriptFile = scriptFolder + "_" + fileRoot + ".cshtml"; - - if (!File.Exists(this.Server.MapPath(scriptFile))) - { - // Try VB (vbhtml) - scriptFile = scriptFolder + "_" + fileRoot + ".vbhtml"; - - if (!File.Exists(this.Server.MapPath(scriptFile))) - { - // Return "" - scriptFile = string.Empty; - } - } - - return scriptFile; - } + [DnnDeprecated(9, 3, 2, "Use Razor Pages instead")] + public partial class RazorModuleBase : ModuleUserControlBase + { + protected virtual string RazorScriptFile + { + get + { + var scriptFolder = this.AppRelativeTemplateSourceDirectory; + var fileRoot = Path.GetFileNameWithoutExtension(this.AppRelativeVirtualPath); + var scriptFile = scriptFolder + "_" + fileRoot + ".cshtml"; + + if (!File.Exists(this.Server.MapPath(scriptFile))) + { + // Try VB (vbhtml) + scriptFile = scriptFolder + "_" + fileRoot + ".vbhtml"; + + if (!File.Exists(this.Server.MapPath(scriptFile))) + { + // Return "" + scriptFile = string.Empty; + } + } + + return scriptFile; + } } /// - [Obsolete("Deprecated in 9.3.2, will be removed in 11.0.0, use Razor Pages instead")] - protected override void OnPreRender(EventArgs e) - { - base.OnPreRender(e); - try - { - if (!string.IsNullOrEmpty(this.RazorScriptFile)) - { - var razorEngine = new RazorEngine(this.RazorScriptFile, this.ModuleContext, this.LocalResourceFile); - var writer = new StringWriter(); - razorEngine.Render(writer); - - this.Controls.Add(new LiteralControl(writer.ToString())); - } - } - catch (Exception ex) - { - Exceptions.ProcessModuleLoadException(this, ex); - } - } - } -} + [DnnDeprecated(9, 3, 2, "Use Razor Pages instead")] + protected override partial void OnPreRender(EventArgs e) + { + base.OnPreRender(e); + try + { + if (!string.IsNullOrEmpty(this.RazorScriptFile)) + { + var razorEngine = new RazorEngine(this.RazorScriptFile, this.ModuleContext, this.LocalResourceFile); + var writer = new StringWriter(); + razorEngine.Render(writer); + + this.Controls.Add(new LiteralControl(writer.ToString())); + } + } + catch (Exception ex) + { + Exceptions.ProcessModuleLoadException(this, ex); + } + } + } +} diff --git a/DNN Platform/DotNetNuke.Web.Razor/RazorModuleControlFactory.cs b/DNN Platform/DotNetNuke.Web.Razor/RazorModuleControlFactory.cs index 499279ff402..a0183bfd81a 100644 --- a/DNN Platform/DotNetNuke.Web.Razor/RazorModuleControlFactory.cs +++ b/DNN Platform/DotNetNuke.Web.Razor/RazorModuleControlFactory.cs @@ -2,36 +2,36 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information -namespace DotNetNuke.Web.Razor -{ - using System; - using System.Web.UI; +namespace DotNetNuke.Web.Razor +{ + using System.Web.UI; - using DotNetNuke.Entities.Modules; - using DotNetNuke.UI.Modules; + using DotNetNuke.Entities.Modules; + using DotNetNuke.Internal.SourceGenerators; + using DotNetNuke.UI.Modules; - [Obsolete("Deprecated in 9.3.2, will be removed in 11.0.0, use Razor Pages instead")] - public class RazorModuleControlFactory : BaseModuleControlFactory + [DnnDeprecated(9, 3, 2, "Use Razor Pages instead")] + public partial class RazorModuleControlFactory : BaseModuleControlFactory { /// - [Obsolete("Deprecated in 9.3.2, will be removed in 11.0.0, use Razor Pages instead")] - public override Control CreateControl(TemplateControl containerControl, string controlKey, string controlSrc) - { - return new RazorHostControl("~/" + controlSrc); + [DnnDeprecated(9, 3, 2, "Use Razor Pages instead")] + public override partial Control CreateControl(TemplateControl containerControl, string controlKey, string controlSrc) + { + return new RazorHostControl("~/" + controlSrc); } /// - [Obsolete("Deprecated in 9.3.2, will be removed in 11.0.0, use Razor Pages instead")] - public override Control CreateModuleControl(TemplateControl containerControl, ModuleInfo moduleConfiguration) - { - return this.CreateControl(containerControl, string.Empty, moduleConfiguration.ModuleControl.ControlSrc); + [DnnDeprecated(9, 3, 2, "Use Razor Pages instead")] + public override partial Control CreateModuleControl(TemplateControl containerControl, ModuleInfo moduleConfiguration) + { + return this.CreateControl(containerControl, string.Empty, moduleConfiguration.ModuleControl.ControlSrc); } /// - [Obsolete("Deprecated in 9.3.2, will be removed in 11.0.0, use Razor Pages instead")] - public override Control CreateSettingsControl(TemplateControl containerControl, ModuleInfo moduleConfiguration, string controlSrc) - { - return this.CreateControl(containerControl, string.Empty, controlSrc); - } - } -} + [DnnDeprecated(9, 3, 2, "Use Razor Pages instead")] + public override partial Control CreateSettingsControl(TemplateControl containerControl, ModuleInfo moduleConfiguration, string controlSrc) + { + return this.CreateControl(containerControl, string.Empty, controlSrc); + } + } +} diff --git a/DNN Platform/DotNetNuke.Web/Api/Extensions/StartupExtensions.cs b/DNN Platform/DotNetNuke.Web/Api/Extensions/StartupExtensions.cs index 82c31628c89..c2202c365a9 100644 --- a/DNN Platform/DotNetNuke.Web/Api/Extensions/StartupExtensions.cs +++ b/DNN Platform/DotNetNuke.Web/Api/Extensions/StartupExtensions.cs @@ -1,44 +1,37 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information - -namespace DotNetNuke.Web.Extensions -{ - using System; - using System.Linq; +namespace DotNetNuke.Web.Extensions +{ + using System.Linq; using DotNetNuke.DependencyInjection.Extensions; using DotNetNuke.Instrumentation; - using DotNetNuke.Web.Api; - using Microsoft.Extensions.DependencyInjection; - using Microsoft.Extensions.DependencyInjection.Extensions; + using DotNetNuke.Web.Api; + + using Microsoft.Extensions.DependencyInjection; + using Microsoft.Extensions.DependencyInjection.Extensions; - /// - /// Adds DNN Web API Specific startup extensions to simplify the - /// Class. - /// - internal static class StartupExtensions + /// Adds DNN Web API Specific startup extensions to simplify the Class. + internal static class StartupExtensions { private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(StartupExtensions)); - - /// - /// Configures all of the 's to be used - /// with the Service Collection for Dependency Injection. - /// - /// - /// Service Collection used to registering services in the container. - /// - public static void AddWebApi(this IServiceCollection services) - { - var controllerTypes = AppDomain.CurrentDomain.GetAssemblies() - .SelectMany(x => x.SafeGetTypes(Logger)) - .Where(x => typeof(DnnApiController).IsAssignableFrom(x) && - x.IsClass && - !x.IsAbstract); - foreach (var controller in controllerTypes) - { - services.TryAddScoped(controller); - } - } - } -} + + /// Configures all of the 's to be used with the Service Collection for Dependency Injection. + /// Service Collection used to registering services in the container. + public static void AddWebApi(this IServiceCollection services) + { + var allTypes = TypeExtensions.SafeGetTypes(); + allTypes.LogOtherExceptions(Logger); + + var controllerTypes = allTypes.Types + .Where( + type => typeof(DnnApiController).IsAssignableFrom(type) && + type is { IsClass: true, IsAbstract: false }); + foreach (var controller in controllerTypes) + { + services.TryAddScoped(controller); + } + } + } +} diff --git a/DNN Platform/DotNetNuke.Web/Api/PortalAliasRouteManager.cs b/DNN Platform/DotNetNuke.Web/Api/PortalAliasRouteManager.cs index 92588548e1d..5504176fece 100644 --- a/DNN Platform/DotNetNuke.Web/Api/PortalAliasRouteManager.cs +++ b/DNN Platform/DotNetNuke.Web/Api/PortalAliasRouteManager.cs @@ -1,177 +1,178 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information -namespace DotNetNuke.Web.Api -{ - using System; - using System.Collections.Generic; - using System.Globalization; - using System.Linq; - using System.Web.Http.Routing; - - using DotNetNuke.Common; - using DotNetNuke.Common.Internal; - using DotNetNuke.Entities.Portals; - - internal class PortalAliasRouteManager : IPortalAliasRouteManager - { - private List prefixCounts; - - // TODO: this method need remove after drop use old api format. - [Obsolete("Replaced with GetRouteUrl. Scheduled for removal in v11.0.0")] - public static string GetOldRouteUrl(string moduleFolderName, string url, int count) - { - Requires.NotNegative("count", count); - Requires.NotNullOrEmpty("moduleFolderName", moduleFolderName); - - return string.Format("{0}DesktopModules/{1}/API/{2}", new PortalAliasRouteManager().GeneratePrefixString(count), moduleFolderName, url); +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information +namespace DotNetNuke.Web.Api +{ + using System; + using System.Collections.Generic; + using System.Globalization; + using System.Linq; + using System.Web.Http.Routing; + + using DotNetNuke.Common; + using DotNetNuke.Common.Internal; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Internal.SourceGenerators; + + internal partial class PortalAliasRouteManager : IPortalAliasRouteManager + { + private List prefixCounts; + + // TODO: this method need remove after drop use old api format. + [DnnDeprecated(9, 0, 0, "Replaced with GetRouteUrl")] + public static partial string GetOldRouteUrl(string moduleFolderName, string url, int count) + { + Requires.NotNegative("count", count); + Requires.NotNullOrEmpty("moduleFolderName", moduleFolderName); + + return string.Format("{0}DesktopModules/{1}/API/{2}", new PortalAliasRouteManager().GeneratePrefixString(count), moduleFolderName, url); } /// - public string GetRouteName(string moduleFolderName, string routeName, int count) - { - Requires.NotNullOrEmpty("moduleFolderName", moduleFolderName); - Requires.NotNegative("count", count); - - return moduleFolderName + "-" + routeName + "-" + count.ToString(CultureInfo.InvariantCulture); + public string GetRouteName(string moduleFolderName, string routeName, int count) + { + Requires.NotNullOrEmpty("moduleFolderName", moduleFolderName); + Requires.NotNegative("count", count); + + return moduleFolderName + "-" + routeName + "-" + count.ToString(CultureInfo.InvariantCulture); } /// - public string GetRouteName(string moduleFolderName, string routeName, PortalAliasInfo portalAlias) - { - var alias = portalAlias.HTTPAlias; - string appPath = TestableGlobals.Instance.ApplicationPath; - if (!string.IsNullOrEmpty(appPath)) - { - int i = alias.IndexOf(appPath, StringComparison.OrdinalIgnoreCase); - if (i > 0) - { - alias = alias.Remove(i, appPath.Length); - } - } - - return this.GetRouteName(moduleFolderName, routeName, CalcAliasPrefixCount(alias)); + public string GetRouteName(string moduleFolderName, string routeName, PortalAliasInfo portalAlias) + { + var alias = portalAlias.HTTPAlias; + string appPath = TestableGlobals.Instance.ApplicationPath; + if (!string.IsNullOrEmpty(appPath)) + { + int i = alias.IndexOf(appPath, StringComparison.OrdinalIgnoreCase); + if (i > 0) + { + alias = alias.Remove(i, appPath.Length); + } + } + + return this.GetRouteName(moduleFolderName, routeName, CalcAliasPrefixCount(alias)); } /// - public HttpRouteValueDictionary GetAllRouteValues(PortalAliasInfo portalAliasInfo, object routeValues) - { - var allRouteValues = new HttpRouteValueDictionary(routeValues); - - var segments = portalAliasInfo.HTTPAlias.Split('/'); - - if (segments.Length > 1) - { - for (int i = 1; i < segments.Length; i++) - { - var key = "prefix" + (i - 1).ToString(CultureInfo.InvariantCulture); - var value = segments[i]; - allRouteValues.Add(key, value); - } - } - - return allRouteValues; + public HttpRouteValueDictionary GetAllRouteValues(PortalAliasInfo portalAliasInfo, object routeValues) + { + var allRouteValues = new HttpRouteValueDictionary(routeValues); + + var segments = portalAliasInfo.HTTPAlias.Split('/'); + + if (segments.Length > 1) + { + for (int i = 1; i < segments.Length; i++) + { + var key = "prefix" + (i - 1).ToString(CultureInfo.InvariantCulture); + var value = segments[i]; + allRouteValues.Add(key, value); + } + } + + return allRouteValues; } /// - public string GetRouteUrl(string moduleFolderName, string url, int count) - { - Requires.NotNegative("count", count); - Requires.NotNullOrEmpty("moduleFolderName", moduleFolderName); - - return string.Format("{0}API/{1}/{2}", this.GeneratePrefixString(count), moduleFolderName, url); + public string GetRouteUrl(string moduleFolderName, string url, int count) + { + Requires.NotNegative("count", count); + Requires.NotNullOrEmpty("moduleFolderName", moduleFolderName); + + return string.Format("{0}API/{1}/{2}", this.GeneratePrefixString(count), moduleFolderName, url); } /// - public void ClearCachedData() - { - this.prefixCounts = null; + public void ClearCachedData() + { + this.prefixCounts = null; } /// - public IEnumerable GetRoutePrefixCounts() - { - if (this.prefixCounts == null) - { - // prefixCounts are required for each route that is mapped but they only change - // when a new portal is added so cache them until that time - var portals = PortalController.Instance.GetPortals(); - - var segmentCounts1 = new List(); - - foreach (PortalInfo portal in portals) - { - IEnumerable aliases = PortalAliasController.Instance.GetPortalAliasesByPortalId(portal.PortalID).Select(x => x.HTTPAlias); - - aliases = this.StripApplicationPath(aliases); - - foreach (string alias in aliases) - { - var count = CalcAliasPrefixCount(alias); - - if (!segmentCounts1.Contains(count)) - { - segmentCounts1.Add(count); - } - } - } - - IEnumerable segmentCounts = segmentCounts1; - this.prefixCounts = segmentCounts.OrderByDescending(x => x).ToList(); - } - - return this.prefixCounts; - } - - private static int CalcAliasPrefixCount(string alias) - { - return alias.Count(c => c == '/'); - } - - private static IEnumerable StripApplicationPathIterable(IEnumerable aliases, string appPath) - { - foreach (string alias in aliases) - { - int i = alias.IndexOf(appPath, StringComparison.OrdinalIgnoreCase); - - if (i > 0) - { - yield return alias.Remove(i, appPath.Length); - } - else - { - yield return alias; - } - } - } - - private IEnumerable StripApplicationPath(IEnumerable aliases) - { - string appPath = TestableGlobals.Instance.ApplicationPath; - - if (string.IsNullOrEmpty(appPath)) - { - return aliases; - } - - return StripApplicationPathIterable(aliases, appPath); - } - - private string GeneratePrefixString(int count) - { - if (count == 0) - { - return string.Empty; - } - - string prefix = string.Empty; - - for (int i = count - 1; i >= 0; i--) - { - prefix = "{prefix" + i + "}/" + prefix; - } - - return prefix; - } - } -} + public IEnumerable GetRoutePrefixCounts() + { + if (this.prefixCounts == null) + { + // prefixCounts are required for each route that is mapped but they only change + // when a new portal is added so cache them until that time + var portals = PortalController.Instance.GetPortals(); + + var segmentCounts1 = new List(); + + foreach (PortalInfo portal in portals) + { + IEnumerable aliases = PortalAliasController.Instance.GetPortalAliasesByPortalId(portal.PortalID).Select(x => x.HTTPAlias); + + aliases = this.StripApplicationPath(aliases); + + foreach (string alias in aliases) + { + var count = CalcAliasPrefixCount(alias); + + if (!segmentCounts1.Contains(count)) + { + segmentCounts1.Add(count); + } + } + } + + IEnumerable segmentCounts = segmentCounts1; + this.prefixCounts = segmentCounts.OrderByDescending(x => x).ToList(); + } + + return this.prefixCounts; + } + + private static int CalcAliasPrefixCount(string alias) + { + return alias.Count(c => c == '/'); + } + + private static IEnumerable StripApplicationPathIterable(IEnumerable aliases, string appPath) + { + foreach (string alias in aliases) + { + int i = alias.IndexOf(appPath, StringComparison.OrdinalIgnoreCase); + + if (i > 0) + { + yield return alias.Remove(i, appPath.Length); + } + else + { + yield return alias; + } + } + } + + private IEnumerable StripApplicationPath(IEnumerable aliases) + { + string appPath = TestableGlobals.Instance.ApplicationPath; + + if (string.IsNullOrEmpty(appPath)) + { + return aliases; + } + + return StripApplicationPathIterable(aliases, appPath); + } + + private string GeneratePrefixString(int count) + { + if (count == 0) + { + return string.Empty; + } + + string prefix = string.Empty; + + for (int i = count - 1; i >= 0; i--) + { + prefix = "{prefix" + i + "}/" + prefix; + } + + return prefix; + } + } +} diff --git a/DNN Platform/DotNetNuke.Web/DependencyInjectionInitialize.cs b/DNN Platform/DotNetNuke.Web/DependencyInjectionInitialize.cs index 6445bd9ef53..f94919dd0ca 100644 --- a/DNN Platform/DotNetNuke.Web/DependencyInjectionInitialize.cs +++ b/DNN Platform/DotNetNuke.Web/DependencyInjectionInitialize.cs @@ -18,6 +18,7 @@ public static class DependencyInjectionInitialize { private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(DependencyInjectionInitialize)); + /// Gets the service collection (for logging/diagnostics). internal static IServiceCollection ServiceCollection { get; private set; } /// Builds the service provider. @@ -34,13 +35,19 @@ public static IServiceProvider BuildServiceProvider() private static void ConfigureAllStartupServices(IServiceCollection services) { - var startupTypes = AppDomain.CurrentDomain.GetAssemblies() - .OrderBy( - assembly => assembly.FullName.StartsWith("DotNetNuke", StringComparison.OrdinalIgnoreCase) ? 0 : - assembly.FullName.StartsWith("DNN", StringComparison.OrdinalIgnoreCase) ? 1 : 2) - .ThenBy(assembly => assembly.FullName) - .SelectMany(assembly => assembly.SafeGetTypes(Logger).OrderBy(type => type.FullName ?? type.Name)) - .Where(type => typeof(IDnnStartup).IsAssignableFrom(type) && type.IsClass && !type.IsAbstract); + var allTypes = TypeExtensions.SafeGetTypes(); + allTypes.LogOtherExceptions(Logger); + if (allTypes.LoadExceptions.Any()) + { + var messageBuilder = allTypes.LoadExceptions.BuildLoaderExceptionsMessage(); + messageBuilder.Insert(0, "While loading IDnnStartup types, the following assemblies had types that could not be loaded. This is only an issue if these types contain DNN startup logic that could not be loaded:"); + Logger.Warn(messageBuilder.ToString()); + } + + var startupTypes = allTypes.Types + .Where( + type => typeof(IDnnStartup).IsAssignableFrom(type) && + type is { IsClass: true, IsAbstract: false }); var startupInstances = startupTypes.Select(CreateInstance).Where(x => x != null); foreach (var startup in startupInstances) diff --git a/DNN Platform/DotNetNuke.Web/DotNetNuke.Web.csproj b/DNN Platform/DotNetNuke.Web/DotNetNuke.Web.csproj index b16b65bd60b..f7c81bea150 100644 --- a/DNN Platform/DotNetNuke.Web/DotNetNuke.Web.csproj +++ b/DNN Platform/DotNetNuke.Web/DotNetNuke.Web.csproj @@ -56,7 +56,9 @@ bin\DotNetNuke.Web.XML 1591 AllRules.ruleset - 7 + latest + true + CS0618,CS3001,SA1600,SA1601,SA1602,SA1604,SA1606,SA1611,SA1614 pdbonly @@ -67,14 +69,18 @@ bin\DotNetNuke.Web.XML 1591 AllRules.ruleset - 7 + latest + true + CS0618,CS3001,SA1600,SA1601,SA1602,SA1604,SA1606,SA1611,SA1614 1591 AllRules.ruleset + latest AllRules.ruleset + latest @@ -113,7 +119,7 @@ True - ..\..\packages\Newtonsoft.Json.13.0.2\lib\net45\Newtonsoft.Json.dll + ..\..\packages\Newtonsoft.Json.13.0.3\lib\net45\Newtonsoft.Json.dll @@ -432,6 +438,10 @@ + + {5fe5d021-9c8d-47a6-bd34-f328ba3e709c} + DotNetNuke.Internal.SourceGenerators + {6928a9b1-f88a-4581-a132-d3eb38669bb0} DotNetNuke.Abstractions diff --git a/DNN Platform/DotNetNuke.Web/InternalServices/ContentWorkflowServiceController.cs b/DNN Platform/DotNetNuke.Web/InternalServices/ContentWorkflowServiceController.cs index 88fe395a5b7..cee46f166df 100644 --- a/DNN Platform/DotNetNuke.Web/InternalServices/ContentWorkflowServiceController.cs +++ b/DNN Platform/DotNetNuke.Web/InternalServices/ContentWorkflowServiceController.cs @@ -2,151 +2,152 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information -namespace DotNetNuke.Web.InternalServices -{ - using System; - using System.Linq; - using System.Net; - using System.Net.Http; - using System.Web.Http; - - using DotNetNuke.Entities.Content.Workflow; - using DotNetNuke.Entities.Content.Workflow.Dto; - using DotNetNuke.Framework; - using DotNetNuke.Services.Exceptions; - using DotNetNuke.Services.Social.Notifications; - using DotNetNuke.Web.Api; - - [DnnAuthorize] - public class ContentWorkflowServiceController : DnnApiController - { +namespace DotNetNuke.Web.InternalServices +{ + using System; + using System.Linq; + using System.Net; + using System.Net.Http; + using System.Web.Http; + + using DotNetNuke.Entities.Content.Workflow; + using DotNetNuke.Entities.Content.Workflow.Dto; + using DotNetNuke.Framework; + using DotNetNuke.Internal.SourceGenerators; + using DotNetNuke.Services.Exceptions; + using DotNetNuke.Services.Social.Notifications; + using DotNetNuke.Web.Api; + + [DnnAuthorize] + public partial class ContentWorkflowServiceController : DnnApiController + { private readonly IWorkflowEngine workflowEngine; /// Initializes a new instance of the class. - public ContentWorkflowServiceController() - { - this.workflowEngine = WorkflowEngine.Instance; - } - - [HttpPost] + public ContentWorkflowServiceController() + { + this.workflowEngine = WorkflowEngine.Instance; + } + + [HttpPost] + [ValidateAntiForgeryToken] + public HttpResponseMessage Reject(NotificationDTO postData) + { + try + { + var notification = NotificationsController.Instance.GetNotification(postData.NotificationId); + if (notification != null) + { + if (string.IsNullOrEmpty(notification.Context)) + { + return this.Request.CreateResponse(HttpStatusCode.OK, new { Result = "success" }); + } + + string[] parameters = notification.Context.Split(':'); + + var stateTransiction = new StateTransaction + { + ContentItemId = int.Parse(parameters[0]), + CurrentStateId = int.Parse(parameters[2]), + Message = new StateTransactionMessage(), + UserId = this.UserInfo.UserID, + }; + this.workflowEngine.DiscardState(stateTransiction); + + return this.Request.CreateResponse(HttpStatusCode.OK, new { Result = "success" }); + } + } + catch (Exception exc) + { + Exceptions.LogException(exc); + } + + return this.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "unable to process notification"); + } + + [HttpPost] [ValidateAntiForgeryToken] - public HttpResponseMessage Reject(NotificationDTO postData) - { - try - { - var notification = NotificationsController.Instance.GetNotification(postData.NotificationId); - if (notification != null) - { - if (string.IsNullOrEmpty(notification.Context)) - { - return this.Request.CreateResponse(HttpStatusCode.OK, new { Result = "success" }); - } - - string[] parameters = notification.Context.Split(':'); - - var stateTransiction = new StateTransaction - { - ContentItemId = int.Parse(parameters[0]), - CurrentStateId = int.Parse(parameters[2]), - Message = new StateTransactionMessage(), - UserId = this.UserInfo.UserID, - }; - this.workflowEngine.DiscardState(stateTransiction); - - return this.Request.CreateResponse(HttpStatusCode.OK, new { Result = "success" }); - } - } - catch (Exception exc) - { - Exceptions.LogException(exc); - } - - return this.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "unable to process notification"); - } - - [HttpPost] + public HttpResponseMessage Approve(NotificationDTO postData) + { + try + { + var notification = NotificationsController.Instance.GetNotification(postData.NotificationId); + if (notification != null) + { + if (string.IsNullOrEmpty(notification.Context)) + { + return this.Request.CreateResponse(HttpStatusCode.OK, new { Result = "success" }); + } + + string[] parameters = notification.Context.Split(':'); + + var stateTransiction = new StateTransaction + { + ContentItemId = int.Parse(parameters[0]), + CurrentStateId = int.Parse(parameters[2]), + Message = new StateTransactionMessage(), + UserId = this.UserInfo.UserID, + }; + this.workflowEngine.CompleteState(stateTransiction); + + return this.Request.CreateResponse(HttpStatusCode.OK, new { Result = "success" }); + } + } + catch (Exception exc) + { + Exceptions.LogException(exc); + } + + return this.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "unable to process notification"); + } + + [DnnDeprecated(7, 4, 0, "No replacement")] + [HttpPost] [ValidateAntiForgeryToken] - public HttpResponseMessage Approve(NotificationDTO postData) - { - try - { - var notification = NotificationsController.Instance.GetNotification(postData.NotificationId); - if (notification != null) - { - if (string.IsNullOrEmpty(notification.Context)) - { - return this.Request.CreateResponse(HttpStatusCode.OK, new { Result = "success" }); - } - - string[] parameters = notification.Context.Split(':'); - - var stateTransiction = new StateTransaction - { - ContentItemId = int.Parse(parameters[0]), - CurrentStateId = int.Parse(parameters[2]), - Message = new StateTransactionMessage(), - UserId = this.UserInfo.UserID, - }; - this.workflowEngine.CompleteState(stateTransiction); - - return this.Request.CreateResponse(HttpStatusCode.OK, new { Result = "success" }); - } - } - catch (Exception exc) - { - Exceptions.LogException(exc); - } - - return this.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "unable to process notification"); - } - - [Obsolete("Obsolted in Platform 7.4.0. Scheduled removal in v10.0.0.")] - [HttpPost] - [ValidateAntiForgeryToken] - public HttpResponseMessage Review(NotificationDTO postData) - { - try - { - var notification = NotificationsController.Instance.GetNotification(postData.NotificationId); - - if (notification != null) - { - if (string.IsNullOrEmpty(notification.Context)) - { - return this.Request.CreateResponse(HttpStatusCode.OK, new { Result = "success" }); - } - - var source = notification.Context; - string[] parameters = null; - if (notification.Context.Contains(";")) - { - parameters = notification.Context.Split(';'); - source = parameters[0]; - parameters = parameters.ToList().Skip(1).ToArray(); - } - - var workflow = ContentWorkflowController.Instance.GetDefaultWorkflow(this.PortalSettings.PortalId); - var workflowSource = ContentWorkflowController.Instance.GetWorkflowSource(workflow.WorkflowID, source); - if (workflowSource == null) - { - return this.Request.CreateResponse(HttpStatusCode.OK, new { Result = "success" }); - } - - var sourceAction = Reflection.CreateInstance(Reflection.CreateType(workflowSource.SourceType)) as IContentWorkflowAction; - if (sourceAction == null) - { - return this.Request.CreateResponse(HttpStatusCode.OK, new { Result = "success" }); - } - - return this.Request.CreateResponse(HttpStatusCode.OK, new { Result = "success", Link = sourceAction.GetAction(parameters) }); - } - } - catch (Exception exc) - { - Exceptions.LogException(exc); - } - - return this.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "unable to process notification"); - } - } -} + public partial HttpResponseMessage Review(NotificationDTO postData) + { + try + { + var notification = NotificationsController.Instance.GetNotification(postData.NotificationId); + + if (notification != null) + { + if (string.IsNullOrEmpty(notification.Context)) + { + return this.Request.CreateResponse(HttpStatusCode.OK, new { Result = "success" }); + } + + var source = notification.Context; + string[] parameters = null; + if (notification.Context.Contains(";")) + { + parameters = notification.Context.Split(';'); + source = parameters[0]; + parameters = parameters.ToList().Skip(1).ToArray(); + } + + var workflow = ContentWorkflowController.Instance.GetDefaultWorkflow(this.PortalSettings.PortalId); + var workflowSource = ContentWorkflowController.Instance.GetWorkflowSource(workflow.WorkflowID, source); + if (workflowSource == null) + { + return this.Request.CreateResponse(HttpStatusCode.OK, new { Result = "success" }); + } + + var sourceAction = Reflection.CreateInstance(Reflection.CreateType(workflowSource.SourceType)) as IContentWorkflowAction; + if (sourceAction == null) + { + return this.Request.CreateResponse(HttpStatusCode.OK, new { Result = "success" }); + } + + return this.Request.CreateResponse(HttpStatusCode.OK, new { Result = "success", Link = sourceAction.GetAction(parameters) }); + } + } + catch (Exception exc) + { + Exceptions.LogException(exc); + } + + return this.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "unable to process notification"); + } + } +} diff --git a/DNN Platform/DotNetNuke.Web/Mvp/AttributeBasedViewStateSerializer.cs b/DNN Platform/DotNetNuke.Web/Mvp/AttributeBasedViewStateSerializer.cs index 5ac739ce367..3b59f39d507 100644 --- a/DNN Platform/DotNetNuke.Web/Mvp/AttributeBasedViewStateSerializer.cs +++ b/DNN Platform/DotNetNuke.Web/Mvp/AttributeBasedViewStateSerializer.cs @@ -1,64 +1,66 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information -namespace DotNetNuke.Web.Mvp -{ - using System; - using System.Linq; - using System.Reflection; +namespace DotNetNuke.Web.Mvp +{ + using System; + using System.Linq; + using System.Reflection; using System.Web.UI; - [Obsolete("Deprecated in DNN 9.2.0. Replace WebFormsMvp and DotNetNuke.Web.Mvp with MVC or SPA patterns instead. Scheduled removal in v11.0.0.")] - public class AttributeBasedViewStateSerializer - { - private const BindingFlags MemberBindingFlags = BindingFlags.Instance | BindingFlags.Public; - - public static void DeSerialize(object value, StateBag state) - { - Type typ = value.GetType(); - - // Parse all the Public instance properties - foreach (PropertyInfo member in typ.GetProperties(MemberBindingFlags)) - { - // Determine if they are attributed with a ViewState Attribute - ViewStateAttribute attr = member.GetCustomAttributes(typeof(ViewStateAttribute), true).OfType().FirstOrDefault(); - if (attr != null) - { - // Get object from ViewState bag - string viewStateKey = attr.ViewStateKey; - if (string.IsNullOrEmpty(viewStateKey)) - { - // Use class member's name for Key - viewStateKey = member.Name; - } - - member.SetValue(value, state[viewStateKey], null); - } - } - } - - public static void Serialize(object value, StateBag state) - { - Type typ = value.GetType(); - - // Parse all the Public instance properties - foreach (PropertyInfo member in typ.GetProperties(MemberBindingFlags)) - { - // Determine if they are attributed with a ViewState Attribute - ViewStateAttribute attr = member.GetCustomAttributes(typeof(ViewStateAttribute), true).OfType().FirstOrDefault(); - if (attr != null) - { - // Add property to ViewState bag - string viewStateKey = attr.ViewStateKey; - if (string.IsNullOrEmpty(viewStateKey)) - { - // Use class member's name for Key - viewStateKey = member.Name; - } - - state[viewStateKey] = member.GetValue(value, null); - } - } - } - } -} + using DotNetNuke.Internal.SourceGenerators; + + [DnnDeprecated(9, 2, 0, "Replace WebFormsMvp and DotNetNuke.Web.Mvp with MVC or SPA patterns instead")] + public partial class AttributeBasedViewStateSerializer + { + private const BindingFlags MemberBindingFlags = BindingFlags.Instance | BindingFlags.Public; + + public static void DeSerialize(object value, StateBag state) + { + Type typ = value.GetType(); + + // Parse all the Public instance properties + foreach (PropertyInfo member in typ.GetProperties(MemberBindingFlags)) + { + // Determine if they are attributed with a ViewState Attribute + ViewStateAttribute attr = member.GetCustomAttributes(typeof(ViewStateAttribute), true).OfType().FirstOrDefault(); + if (attr != null) + { + // Get object from ViewState bag + string viewStateKey = attr.ViewStateKey; + if (string.IsNullOrEmpty(viewStateKey)) + { + // Use class member's name for Key + viewStateKey = member.Name; + } + + member.SetValue(value, state[viewStateKey], null); + } + } + } + + public static void Serialize(object value, StateBag state) + { + Type typ = value.GetType(); + + // Parse all the Public instance properties + foreach (PropertyInfo member in typ.GetProperties(MemberBindingFlags)) + { + // Determine if they are attributed with a ViewState Attribute + ViewStateAttribute attr = member.GetCustomAttributes(typeof(ViewStateAttribute), true).OfType().FirstOrDefault(); + if (attr != null) + { + // Add property to ViewState bag + string viewStateKey = attr.ViewStateKey; + if (string.IsNullOrEmpty(viewStateKey)) + { + // Use class member's name for Key + viewStateKey = member.Name; + } + + state[viewStateKey] = member.GetValue(value, null); + } + } + } + } +} diff --git a/DNN Platform/DotNetNuke.Web/Mvp/HttpHandlerPresenter.cs b/DNN Platform/DotNetNuke.Web/Mvp/HttpHandlerPresenter.cs index 484cf984e94..a103d4c1ee1 100644 --- a/DNN Platform/DotNetNuke.Web/Mvp/HttpHandlerPresenter.cs +++ b/DNN Platform/DotNetNuke.Web/Mvp/HttpHandlerPresenter.cs @@ -2,21 +2,21 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information -namespace DotNetNuke.Web.Mvp -{ - using System; +namespace DotNetNuke.Web.Mvp +{ + using DotNetNuke.Internal.SourceGenerators; - using WebFormsMvp; + using WebFormsMvp; - [Obsolete("Deprecated in DNN 9.2.0. Replace WebFormsMvp and DotNetNuke.Web.Mvp with MVC or SPA patterns instead. Scheduled removal in v11.0.0.")] - public abstract class HttpHandlerPresenter : Presenter + [DnnDeprecated(9, 2, 0, "Replace WebFormsMvp and DotNetNuke.Web.Mvp with MVC or SPA patterns instead")] + public abstract partial class HttpHandlerPresenter : Presenter where TView : class, IHttpHandlerView { /// Initializes a new instance of the class. /// The view. - protected HttpHandlerPresenter(TView view) - : base(view) - { - } - } -} + protected HttpHandlerPresenter(TView view) + : base(view) + { + } + } +} diff --git a/DNN Platform/DotNetNuke.Web/Mvp/HttpHandlerView.cs b/DNN Platform/DotNetNuke.Web/Mvp/HttpHandlerView.cs index d8558a0d083..0b525bc4be1 100644 --- a/DNN Platform/DotNetNuke.Web/Mvp/HttpHandlerView.cs +++ b/DNN Platform/DotNetNuke.Web/Mvp/HttpHandlerView.cs @@ -4,13 +4,13 @@ namespace DotNetNuke.Web.Mvp { - using System; + using DotNetNuke.Internal.SourceGenerators; using WebFormsMvp.Web; /// Implements a custom HTTP handler for a WebForms Model-View-Presenter. - [Obsolete("Deprecated in DNN 9.2.0. Replace WebFormsMvp and DotNetNuke.Web.Mvp with MVC or SPA patterns instead. Scheduled removal in v11.0.0.")] - public abstract class HttpHandlerView : MvpHttpHandler, IHttpHandlerView + [DnnDeprecated(9, 2, 0, "Replace WebFormsMvp and DotNetNuke.Web.Mvp with MVC or SPA patterns instead")] + public abstract partial class HttpHandlerView : MvpHttpHandler, IHttpHandlerView { } } diff --git a/DNN Platform/DotNetNuke.Web/Mvp/IHttpHandlerView.cs b/DNN Platform/DotNetNuke.Web/Mvp/IHttpHandlerView.cs index bdea3ee9d73..f306b1430a7 100644 --- a/DNN Platform/DotNetNuke.Web/Mvp/IHttpHandlerView.cs +++ b/DNN Platform/DotNetNuke.Web/Mvp/IHttpHandlerView.cs @@ -2,15 +2,15 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information -namespace DotNetNuke.Web.Mvp -{ - using System; +namespace DotNetNuke.Web.Mvp +{ + using DotNetNuke.Internal.SourceGenerators; - using WebFormsMvp; + using WebFormsMvp; /// Http handler of an WebForms MVP View. - [Obsolete("Deprecated in DNN 9.2.0. Replace WebFormsMvp and DotNetNuke.Web.Mvp with MVC or SPA patterns instead. Scheduled removal in v11.0.0.")] - public interface IHttpHandlerView : IView + [DnnDeprecated(9, 2, 0, "Replace WebFormsMvp and DotNetNuke.Web.Mvp with MVC or SPA patterns instead")] + public partial interface IHttpHandlerView : IView { } -} +} diff --git a/DNN Platform/DotNetNuke.Web/Mvp/IModuleView.cs b/DNN Platform/DotNetNuke.Web/Mvp/IModuleView.cs index 14cfe4c9977..9f1596c4a25 100644 --- a/DNN Platform/DotNetNuke.Web/Mvp/IModuleView.cs +++ b/DNN Platform/DotNetNuke.Web/Mvp/IModuleView.cs @@ -3,10 +3,10 @@ // See the LICENSE file in the project root for more information namespace DotNetNuke.Web.Mvp { - using System; + using DotNetNuke.Internal.SourceGenerators; - [Obsolete("Deprecated in DNN 9.2.0. Replace WebFormsMvp and DotNetNuke.Web.Mvp with MVC or SPA patterns instead. Scheduled removal in v11.0.0.")] - public interface IModuleView : IModuleViewBase + [DnnDeprecated(9, 2, 0, "Replace WebFormsMvp and DotNetNuke.Web.Mvp with MVC or SPA patterns instead")] + public partial interface IModuleView : IModuleViewBase { } } diff --git a/DNN Platform/DotNetNuke.Web/Mvp/IModuleViewBase.cs b/DNN Platform/DotNetNuke.Web/Mvp/IModuleViewBase.cs index 949e41d2c60..62b0e4701ad 100644 --- a/DNN Platform/DotNetNuke.Web/Mvp/IModuleViewBase.cs +++ b/DNN Platform/DotNetNuke.Web/Mvp/IModuleViewBase.cs @@ -1,22 +1,23 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information -namespace DotNetNuke.Web.Mvp -{ - using System; +namespace DotNetNuke.Web.Mvp +{ + using System; - using DotNetNuke.UI.Skins.Controls; + using DotNetNuke.Internal.SourceGenerators; + using DotNetNuke.UI.Skins.Controls; using WebFormsMvp; - [Obsolete("Deprecated in DNN 9.2.0. Replace WebFormsMvp and DotNetNuke.Web.Mvp with MVC or SPA patterns instead. Scheduled removal in v11.0.0.")] - public interface IModuleViewBase : IView - { - event EventHandler Initialize; - - bool AutoDataBind { get; set; } - - void ProcessModuleLoadException(Exception ex); - - void ShowMessage(string messageHeader, string message, ModuleMessage.ModuleMessageType messageType); - } -} + [DnnDeprecated(9, 2, 0, "Replace WebFormsMvp and DotNetNuke.Web.Mvp with MVC or SPA patterns instead")] + public partial interface IModuleViewBase : IView + { + event EventHandler Initialize; + + bool AutoDataBind { get; set; } + + void ProcessModuleLoadException(Exception ex); + + void ShowMessage(string messageHeader, string message, ModuleMessage.ModuleMessageType messageType); + } +} diff --git a/DNN Platform/DotNetNuke.Web/Mvp/IModuleView{TModel}.cs b/DNN Platform/DotNetNuke.Web/Mvp/IModuleView{TModel}.cs index 0ed9480f7ba..ebca359fb72 100644 --- a/DNN Platform/DotNetNuke.Web/Mvp/IModuleView{TModel}.cs +++ b/DNN Platform/DotNetNuke.Web/Mvp/IModuleView{TModel}.cs @@ -3,12 +3,12 @@ // See the LICENSE file in the project root for more information namespace DotNetNuke.Web.Mvp { - using System; + using DotNetNuke.Internal.SourceGenerators; using WebFormsMvp; - [Obsolete("Deprecated in DNN 9.2.0. Replace WebFormsMvp and DotNetNuke.Web.Mvp with MVC or SPA patterns instead. Scheduled removal in v11.0.0.")] - public interface IModuleView : IModuleViewBase, IView + [DnnDeprecated(9, 2, 0, "Replace WebFormsMvp and DotNetNuke.Web.Mvp with MVC or SPA patterns instead")] + public partial interface IModuleView : IModuleViewBase, IView where TModel : class, new() { } diff --git a/DNN Platform/DotNetNuke.Web/Mvp/ISettingsView.cs b/DNN Platform/DotNetNuke.Web/Mvp/ISettingsView.cs index 9f4ca89c5b6..42ab8ff8251 100644 --- a/DNN Platform/DotNetNuke.Web/Mvp/ISettingsView.cs +++ b/DNN Platform/DotNetNuke.Web/Mvp/ISettingsView.cs @@ -2,15 +2,17 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information -namespace DotNetNuke.Web.Mvp -{ - using System; +namespace DotNetNuke.Web.Mvp +{ + using System; - [Obsolete("Deprecated in DNN 9.2.0. Replace WebFormsMvp and DotNetNuke.Web.Mvp with MVC or SPA patterns instead. Scheduled removal in v11.0.0.")] - public interface ISettingsView : IModuleViewBase - { - event EventHandler OnLoadSettings; - - event EventHandler OnSaveSettings; - } -} + using DotNetNuke.Internal.SourceGenerators; + + [DnnDeprecated(9, 2, 0, "Replace WebFormsMvp and DotNetNuke.Web.Mvp with MVC or SPA patterns instead")] + public partial interface ISettingsView : IModuleViewBase + { + event EventHandler OnLoadSettings; + + event EventHandler OnSaveSettings; + } +} diff --git a/DNN Platform/DotNetNuke.Web/Mvp/ISettingsView{TModel}.cs b/DNN Platform/DotNetNuke.Web/Mvp/ISettingsView{TModel}.cs index 68831ef27c0..4381f6f19bb 100644 --- a/DNN Platform/DotNetNuke.Web/Mvp/ISettingsView{TModel}.cs +++ b/DNN Platform/DotNetNuke.Web/Mvp/ISettingsView{TModel}.cs @@ -6,10 +6,12 @@ namespace DotNetNuke.Web.Mvp { using System; + using DotNetNuke.Internal.SourceGenerators; + using WebFormsMvp; - [Obsolete("Deprecated in DNN 9.2.0. Replace WebFormsMvp and DotNetNuke.Web.Mvp with MVC or SPA patterns instead. Scheduled removal in v11.0.0.")] - public interface ISettingsView : IModuleViewBase, IView + [DnnDeprecated(9, 2, 0, "Replace WebFormsMvp and DotNetNuke.Web.Mvp with MVC or SPA patterns instead")] + public partial interface ISettingsView : IModuleViewBase, IView where TModel : class, new() { event EventHandler OnLoadSettings; diff --git a/DNN Platform/DotNetNuke.Web/Mvp/IWebServiceView.cs b/DNN Platform/DotNetNuke.Web/Mvp/IWebServiceView.cs index faf61cf1d53..488f6edf65f 100644 --- a/DNN Platform/DotNetNuke.Web/Mvp/IWebServiceView.cs +++ b/DNN Platform/DotNetNuke.Web/Mvp/IWebServiceView.cs @@ -2,12 +2,12 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information -namespace DotNetNuke.Web.Mvp -{ - using System; +namespace DotNetNuke.Web.Mvp +{ + using DotNetNuke.Internal.SourceGenerators; - [Obsolete("Deprecated in DNN 9.2.0. Replace WebFormsMvp and DotNetNuke.Web.Mvp with MVC or SPA patterns instead. Scheduled removal in v11.0.0.")] - public interface IWebServiceView : IWebServiceViewBase + [DnnDeprecated(9, 2, 0, "Replace WebFormsMvp and DotNetNuke.Web.Mvp with MVC or SPA patterns instead")] + public partial interface IWebServiceView : IWebServiceViewBase { } -} +} diff --git a/DNN Platform/DotNetNuke.Web/Mvp/IWebServiceViewBase.cs b/DNN Platform/DotNetNuke.Web/Mvp/IWebServiceViewBase.cs index d94640aa568..beaea9d70cd 100644 --- a/DNN Platform/DotNetNuke.Web/Mvp/IWebServiceViewBase.cs +++ b/DNN Platform/DotNetNuke.Web/Mvp/IWebServiceViewBase.cs @@ -2,14 +2,14 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information -namespace DotNetNuke.Web.Mvp -{ - using System; +namespace DotNetNuke.Web.Mvp +{ + using DotNetNuke.Internal.SourceGenerators; - using WebFormsMvp; + using WebFormsMvp; - [Obsolete("Deprecated in DNN 9.2.0. Replace WebFormsMvp and DotNetNuke.Web.Mvp with MVC or SPA patterns instead. Scheduled removal in v11.0.0.")] - public interface IWebServiceViewBase : IView + [DnnDeprecated(9, 2, 0, "Replace WebFormsMvp and DotNetNuke.Web.Mvp with MVC or SPA patterns instead")] + public partial interface IWebServiceViewBase : IView { } -} +} diff --git a/DNN Platform/DotNetNuke.Web/Mvp/IWebServiceView{TModel}.cs b/DNN Platform/DotNetNuke.Web/Mvp/IWebServiceView{TModel}.cs index c0da01e6905..dd2ac4338cf 100644 --- a/DNN Platform/DotNetNuke.Web/Mvp/IWebServiceView{TModel}.cs +++ b/DNN Platform/DotNetNuke.Web/Mvp/IWebServiceView{TModel}.cs @@ -4,12 +4,12 @@ namespace DotNetNuke.Web.Mvp { - using System; + using DotNetNuke.Internal.SourceGenerators; using WebFormsMvp; - [Obsolete("Deprecated in DNN 9.2.0. Replace WebFormsMvp and DotNetNuke.Web.Mvp with MVC or SPA patterns instead. Scheduled removal in v11.0.0.")] - public interface IWebServiceView : IWebServiceViewBase, IView + [DnnDeprecated(9, 2, 0, "Replace WebFormsMvp and DotNetNuke.Web.Mvp with MVC or SPA patterns instead")] + public partial interface IWebServiceView : IWebServiceViewBase, IView where TModel : class, new() { } diff --git a/DNN Platform/DotNetNuke.Web/Mvp/ModulePresenter.cs b/DNN Platform/DotNetNuke.Web/Mvp/ModulePresenter.cs index d11d36c931b..56731bdc5a6 100644 --- a/DNN Platform/DotNetNuke.Web/Mvp/ModulePresenter.cs +++ b/DNN Platform/DotNetNuke.Web/Mvp/ModulePresenter.cs @@ -2,12 +2,12 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information -namespace DotNetNuke.Web.Mvp -{ - using System; +namespace DotNetNuke.Web.Mvp +{ + using DotNetNuke.Internal.SourceGenerators; - [Obsolete("Deprecated in DNN 9.2.0. Replace WebFormsMvp and DotNetNuke.Web.Mvp with MVC or SPA patterns instead. Scheduled removal in v11.0.0.")] - public abstract class ModulePresenter : ModulePresenterBase + [DnnDeprecated(9, 2, 0, "Replace WebFormsMvp and DotNetNuke.Web.Mvp with MVC or SPA patterns instead")] + public abstract partial class ModulePresenter : ModulePresenterBase where TView : class, IModuleView { /// Initializes a new instance of the class. @@ -16,5 +16,5 @@ protected ModulePresenter(TView view) : base(view) { } - } -} + } +} diff --git a/DNN Platform/DotNetNuke.Web/Mvp/ModulePresenterBase.cs b/DNN Platform/DotNetNuke.Web/Mvp/ModulePresenterBase.cs index 8077433d86c..05005493d09 100644 --- a/DNN Platform/DotNetNuke.Web/Mvp/ModulePresenterBase.cs +++ b/DNN Platform/DotNetNuke.Web/Mvp/ModulePresenterBase.cs @@ -1,234 +1,235 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information -namespace DotNetNuke.Web.Mvp -{ - using System; - using System.Collections.Generic; - using System.Web.UI; - - using DotNetNuke.Common.Internal; - using DotNetNuke.Common.Utilities; - using DotNetNuke.Entities.Modules; - using DotNetNuke.Services.Localization; - using DotNetNuke.UI.Modules; - using DotNetNuke.UI.Skins.Controls; - using DotNetNuke.Web.Validators; +namespace DotNetNuke.Web.Mvp +{ + using System; + using System.Collections.Generic; + using System.Web.UI; + + using DotNetNuke.Common.Internal; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Modules; + using DotNetNuke.Internal.SourceGenerators; + using DotNetNuke.Services.Localization; + using DotNetNuke.UI.Modules; + using DotNetNuke.UI.Skins.Controls; + using DotNetNuke.Web.Validators; using WebFormsMvp; - [Obsolete("Deprecated in DNN 9.2.0. Replace WebFormsMvp and DotNetNuke.Web.Mvp with MVC or SPA patterns instead. Scheduled removal in v11.0.0.")] - public abstract class ModulePresenterBase : Presenter + [DnnDeprecated(9, 2, 0, "Replace WebFormsMvp and DotNetNuke.Web.Mvp with MVC or SPA patterns instead")] + public abstract partial class ModulePresenterBase : Presenter where TView : class, IModuleViewBase { /// Initializes a new instance of the class. /// The view. - protected ModulePresenterBase(TView view) - : base(view) - { - // Try and cast view to Control to get common control properties - var control = view as Control; - if (control != null && control.Page != null) - { - this.IsPostBack = control.Page.IsPostBack; - } - - // Try and cast view to IModuleControl to get the Context - var moduleControl = view as IModuleControl; - if (moduleControl != null) - { - this.LocalResourceFile = moduleControl.LocalResourceFile; - this.ModuleContext = moduleControl.ModuleContext; - } - - this.Validator = new Validator(new DataAnnotationsObjectValidator()); - - view.Initialize += this.InitializeInternal; - view.Load += this.LoadInternal; - } - - public bool AutoDataBind { get; set; } - - public ModuleInfo ModuleInfo { get; set; } - - public bool IsEditable { get; set; } - - public bool IsPostBack { get; set; } - - public bool IsSuperUser { get; set; } - - public string LocalResourceFile { get; set; } - - public ModuleInstanceContext ModuleContext { get; set; } - - public int ModuleId { get; set; } - - public int PortalId { get; set; } - - public int TabId { get; set; } - - public int UserId { get; set; } - - public Dictionary Settings { get; set; } - - public Validator Validator { get; set; } - - protected internal virtual bool AllowAnonymousAccess - { - get - { - return true; - } - } - - protected internal virtual bool IsUserAuthorized - { - get - { - return true; - } - } - - public virtual void RestoreState(StateBag stateBag) - { - AttributeBasedViewStateSerializer.DeSerialize(this, stateBag); - } - - public virtual void SaveState(StateBag stateBag) - { - AttributeBasedViewStateSerializer.Serialize(this, stateBag); - } - - protected internal virtual bool CheckAuthPolicy() - { - if (this.UserId == Null.NullInteger && !this.AllowAnonymousAccess) - { - this.OnNoCurrentUser(); - return false; - } - - if (!this.IsUserAuthorized) - { - this.OnUnauthorizedUser(); - return false; - } - - return true; - } - - protected virtual void LoadFromContext() - { - if (this.ModuleContext != null) - { - this.ModuleInfo = this.ModuleContext.Configuration; - this.IsEditable = this.ModuleContext.IsEditable; - this.IsSuperUser = this.ModuleContext.PortalSettings.UserInfo.IsSuperUser; - this.ModuleId = this.ModuleContext.ModuleId; - this.PortalId = this.ModuleContext.PortalId; - this.Settings = new Dictionary(); - foreach (object key in this.ModuleContext.Settings.Keys) - { - this.Settings[key.ToString()] = (string)this.ModuleContext.Settings[key]; - } - - this.TabId = this.ModuleContext.TabId; - this.UserId = this.ModuleContext.PortalSettings.UserInfo.UserID; - } - } - - protected virtual string LocalizeString(string key) - { - string localizedString; - if (!string.IsNullOrEmpty(key) && !string.IsNullOrEmpty(this.LocalResourceFile)) - { - localizedString = Localization.GetString(key, this.LocalResourceFile); - } - else - { - localizedString = Null.NullString; - } - - return localizedString; - } - - protected virtual void OnInit() - { - } - - protected virtual void OnLoad() - { - } - - protected virtual void OnNoCurrentUser() - { - this.RedirectToLogin(); - } - - protected virtual void OnUnauthorizedUser() - { - this.RedirectToAccessDenied(); - } - - protected void RedirectToAccessDenied() - { - this.Response.Redirect(TestableGlobals.Instance.AccessDeniedURL(), true); - } - - protected void RedirectToCurrentPage() - { - this.Response.Redirect(TestableGlobals.Instance.NavigateURL(), true); - } - - protected void RedirectToLogin() - { - this.Response.Redirect(TestableGlobals.Instance.LoginURL(this.Request.RawUrl, false), true); - } - - protected void ProcessModuleLoadException(Exception ex) - { - this.View.ProcessModuleLoadException(ex); - } - - protected void ShowMessage(string messageHeader, string message, ModuleMessage.ModuleMessageType messageType) - { - this.ShowMessage(messageHeader, message, messageType, true); - } - - protected void ShowMessage(string message, ModuleMessage.ModuleMessageType messageType) - { - this.ShowMessage(message, messageType, true); - } - - protected void ShowMessage(string message, ModuleMessage.ModuleMessageType messageType, bool localize) - { - this.ShowMessage(string.Empty, message, messageType, localize); - } - - protected void ShowMessage(string messageHeader, string message, ModuleMessage.ModuleMessageType messageType, bool localize) - { - if (!string.IsNullOrEmpty(message)) - { - if (localize) - { - messageHeader = this.LocalizeString(messageHeader); - message = this.LocalizeString(message); - } - - this.View.ShowMessage(messageHeader, message, messageType); - } - } - - private void InitializeInternal(object sender, EventArgs e) - { - this.LoadFromContext(); - this.OnInit(); - } - - private void LoadInternal(object sender, EventArgs e) - { - if (this.CheckAuthPolicy()) - { - this.OnLoad(); - } - } - } -} + protected ModulePresenterBase(TView view) + : base(view) + { + // Try and cast view to Control to get common control properties + var control = view as Control; + if (control != null && control.Page != null) + { + this.IsPostBack = control.Page.IsPostBack; + } + + // Try and cast view to IModuleControl to get the Context + var moduleControl = view as IModuleControl; + if (moduleControl != null) + { + this.LocalResourceFile = moduleControl.LocalResourceFile; + this.ModuleContext = moduleControl.ModuleContext; + } + + this.Validator = new Validator(new DataAnnotationsObjectValidator()); + + view.Initialize += this.InitializeInternal; + view.Load += this.LoadInternal; + } + + public bool AutoDataBind { get; set; } + + public ModuleInfo ModuleInfo { get; set; } + + public bool IsEditable { get; set; } + + public bool IsPostBack { get; set; } + + public bool IsSuperUser { get; set; } + + public string LocalResourceFile { get; set; } + + public ModuleInstanceContext ModuleContext { get; set; } + + public int ModuleId { get; set; } + + public int PortalId { get; set; } + + public int TabId { get; set; } + + public int UserId { get; set; } + + public Dictionary Settings { get; set; } + + public Validator Validator { get; set; } + + protected internal virtual bool AllowAnonymousAccess + { + get + { + return true; + } + } + + protected internal virtual bool IsUserAuthorized + { + get + { + return true; + } + } + + public virtual void RestoreState(StateBag stateBag) + { + AttributeBasedViewStateSerializer.DeSerialize(this, stateBag); + } + + public virtual void SaveState(StateBag stateBag) + { + AttributeBasedViewStateSerializer.Serialize(this, stateBag); + } + + protected internal virtual bool CheckAuthPolicy() + { + if (this.UserId == Null.NullInteger && !this.AllowAnonymousAccess) + { + this.OnNoCurrentUser(); + return false; + } + + if (!this.IsUserAuthorized) + { + this.OnUnauthorizedUser(); + return false; + } + + return true; + } + + protected virtual void LoadFromContext() + { + if (this.ModuleContext != null) + { + this.ModuleInfo = this.ModuleContext.Configuration; + this.IsEditable = this.ModuleContext.IsEditable; + this.IsSuperUser = this.ModuleContext.PortalSettings.UserInfo.IsSuperUser; + this.ModuleId = this.ModuleContext.ModuleId; + this.PortalId = this.ModuleContext.PortalId; + this.Settings = new Dictionary(); + foreach (object key in this.ModuleContext.Settings.Keys) + { + this.Settings[key.ToString()] = (string)this.ModuleContext.Settings[key]; + } + + this.TabId = this.ModuleContext.TabId; + this.UserId = this.ModuleContext.PortalSettings.UserInfo.UserID; + } + } + + protected virtual string LocalizeString(string key) + { + string localizedString; + if (!string.IsNullOrEmpty(key) && !string.IsNullOrEmpty(this.LocalResourceFile)) + { + localizedString = Localization.GetString(key, this.LocalResourceFile); + } + else + { + localizedString = Null.NullString; + } + + return localizedString; + } + + protected virtual void OnInit() + { + } + + protected virtual void OnLoad() + { + } + + protected virtual void OnNoCurrentUser() + { + this.RedirectToLogin(); + } + + protected virtual void OnUnauthorizedUser() + { + this.RedirectToAccessDenied(); + } + + protected void RedirectToAccessDenied() + { + this.Response.Redirect(TestableGlobals.Instance.AccessDeniedURL(), true); + } + + protected void RedirectToCurrentPage() + { + this.Response.Redirect(TestableGlobals.Instance.NavigateURL(), true); + } + + protected void RedirectToLogin() + { + this.Response.Redirect(TestableGlobals.Instance.LoginURL(this.Request.RawUrl, false), true); + } + + protected void ProcessModuleLoadException(Exception ex) + { + this.View.ProcessModuleLoadException(ex); + } + + protected void ShowMessage(string messageHeader, string message, ModuleMessage.ModuleMessageType messageType) + { + this.ShowMessage(messageHeader, message, messageType, true); + } + + protected void ShowMessage(string message, ModuleMessage.ModuleMessageType messageType) + { + this.ShowMessage(message, messageType, true); + } + + protected void ShowMessage(string message, ModuleMessage.ModuleMessageType messageType, bool localize) + { + this.ShowMessage(string.Empty, message, messageType, localize); + } + + protected void ShowMessage(string messageHeader, string message, ModuleMessage.ModuleMessageType messageType, bool localize) + { + if (!string.IsNullOrEmpty(message)) + { + if (localize) + { + messageHeader = this.LocalizeString(messageHeader); + message = this.LocalizeString(message); + } + + this.View.ShowMessage(messageHeader, message, messageType); + } + } + + private void InitializeInternal(object sender, EventArgs e) + { + this.LoadFromContext(); + this.OnInit(); + } + + private void LoadInternal(object sender, EventArgs e) + { + if (this.CheckAuthPolicy()) + { + this.OnLoad(); + } + } + } +} diff --git a/DNN Platform/DotNetNuke.Web/Mvp/ModulePresenter{TView,TModel}.cs b/DNN Platform/DotNetNuke.Web/Mvp/ModulePresenter{TView,TModel}.cs index aee7908aca4..59e1c63e6e4 100644 --- a/DNN Platform/DotNetNuke.Web/Mvp/ModulePresenter{TView,TModel}.cs +++ b/DNN Platform/DotNetNuke.Web/Mvp/ModulePresenter{TView,TModel}.cs @@ -4,10 +4,10 @@ namespace DotNetNuke.Web.Mvp { - using System; + using DotNetNuke.Internal.SourceGenerators; - [Obsolete("Deprecated in DNN 9.2.0. Replace WebFormsMvp and DotNetNuke.Web.Mvp with MVC or SPA patterns instead. Scheduled removal in v11.0.0.")] - public abstract class ModulePresenter : ModulePresenterBase + [DnnDeprecated(9, 2, 0, "Replace WebFormsMvp and DotNetNuke.Web.Mvp with MVC or SPA patterns instead")] + public abstract partial class ModulePresenter : ModulePresenterBase where TView : class, IModuleView where TModel : class, new() { diff --git a/DNN Platform/DotNetNuke.Web/Mvp/ModuleSettingsPresenterBase{TView}.cs b/DNN Platform/DotNetNuke.Web/Mvp/ModuleSettingsPresenterBase{TView}.cs index af342f70fd5..45efa9a6bd7 100644 --- a/DNN Platform/DotNetNuke.Web/Mvp/ModuleSettingsPresenterBase{TView}.cs +++ b/DNN Platform/DotNetNuke.Web/Mvp/ModuleSettingsPresenterBase{TView}.cs @@ -7,8 +7,10 @@ namespace DotNetNuke.Web.Mvp using System; using System.Collections.Generic; - [Obsolete("Deprecated in DNN 9.2.0. Replace WebFormsMvp and DotNetNuke.Web.Mvp with MVC or SPA patterns instead. Scheduled removal in v11.0.0.")] - public class ModuleSettingsPresenterBase : ModulePresenterBase + using DotNetNuke.Internal.SourceGenerators; + + [DnnDeprecated(9, 2, 0, "Replace WebFormsMvp and DotNetNuke.Web.Mvp with MVC or SPA patterns instead")] + public partial class ModuleSettingsPresenterBase : ModulePresenterBase where TView : class, ISettingsView { /// Initializes a new instance of the class. diff --git a/DNN Platform/DotNetNuke.Web/Mvp/ModuleSettingsPresenter{TView,TModel}.cs b/DNN Platform/DotNetNuke.Web/Mvp/ModuleSettingsPresenter{TView,TModel}.cs index 5f0e8602094..82051c9182e 100644 --- a/DNN Platform/DotNetNuke.Web/Mvp/ModuleSettingsPresenter{TView,TModel}.cs +++ b/DNN Platform/DotNetNuke.Web/Mvp/ModuleSettingsPresenter{TView,TModel}.cs @@ -10,9 +10,10 @@ namespace DotNetNuke.Web.Mvp using System.Linq; using DotNetNuke.Entities.Modules; + using DotNetNuke.Internal.SourceGenerators; - [Obsolete("Deprecated in DNN 9.2.0. Replace WebFormsMvp and DotNetNuke.Web.Mvp with MVC or SPA patterns instead. Scheduled removal in v11.0.0.")] - public abstract class ModuleSettingsPresenter : ModulePresenterBase + [DnnDeprecated(9, 2, 0, "Replace WebFormsMvp and DotNetNuke.Web.Mvp with MVC or SPA patterns instead")] + public abstract partial class ModuleSettingsPresenter : ModulePresenterBase where TView : class, ISettingsView where TModel : SettingsModel, new() { diff --git a/DNN Platform/DotNetNuke.Web/Mvp/ModuleView.cs b/DNN Platform/DotNetNuke.Web/Mvp/ModuleView.cs index beadd01e329..b44e88db42e 100644 --- a/DNN Platform/DotNetNuke.Web/Mvp/ModuleView.cs +++ b/DNN Platform/DotNetNuke.Web/Mvp/ModuleView.cs @@ -2,12 +2,12 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information -namespace DotNetNuke.Web.Mvp -{ - using System; +namespace DotNetNuke.Web.Mvp +{ + using DotNetNuke.Internal.SourceGenerators; - [Obsolete("Deprecated in DNN 9.2.0. Replace WebFormsMvp and DotNetNuke.Web.Mvp with MVC or SPA patterns instead. Scheduled removal in v11.0.0.")] - public abstract class ModuleView : ModuleViewBase + [DnnDeprecated(9, 2, 0, "Replace WebFormsMvp and DotNetNuke.Web.Mvp with MVC or SPA patterns instead")] + public abstract partial class ModuleView : ModuleViewBase { } -} +} diff --git a/DNN Platform/DotNetNuke.Web/Mvp/ModuleViewBase.cs b/DNN Platform/DotNetNuke.Web/Mvp/ModuleViewBase.cs index 12c260ab707..255342d00c7 100644 --- a/DNN Platform/DotNetNuke.Web/Mvp/ModuleViewBase.cs +++ b/DNN Platform/DotNetNuke.Web/Mvp/ModuleViewBase.cs @@ -1,22 +1,23 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information -namespace DotNetNuke.Web.Mvp -{ - using System; - using System.Globalization; - - using DotNetNuke.Services.Exceptions; - using DotNetNuke.UI.Modules; - using DotNetNuke.UI.Skins.Controls; +namespace DotNetNuke.Web.Mvp +{ + using System; + using System.Globalization; + + using DotNetNuke.Internal.SourceGenerators; + using DotNetNuke.Services.Exceptions; + using DotNetNuke.UI.Modules; + using DotNetNuke.UI.Skins.Controls; using WebFormsMvp.Web; - [Obsolete("Deprecated in DNN 9.2.0. Replace WebFormsMvp and DotNetNuke.Web.Mvp with MVC or SPA patterns instead. Scheduled removal in v11.0.0.")] - public abstract class ModuleViewBase : ModuleUserControlBase, IModuleViewBase - { - protected ModuleViewBase() - { - this.AutoDataBind = true; + [DnnDeprecated(9, 2, 0, "Replace WebFormsMvp and DotNetNuke.Web.Mvp with MVC or SPA patterns instead")] + public abstract partial class ModuleViewBase : ModuleUserControlBase, IModuleViewBase + { + protected ModuleViewBase() + { + this.AutoDataBind = true; } /// @@ -26,79 +27,79 @@ protected ModuleViewBase() public new event EventHandler Load; /// - public bool ThrowExceptionIfNoPresenterBound - { - get { return true; } + public bool ThrowExceptionIfNoPresenterBound + { + get { return true; } } /// public bool AutoDataBind { get; set; } /// - public void ProcessModuleLoadException(Exception ex) - { - Exceptions.ProcessModuleLoadException(this, ex); + public void ProcessModuleLoadException(Exception ex) + { + Exceptions.ProcessModuleLoadException(this, ex); } /// - public void ShowMessage(string messageHeader, string message, ModuleMessage.ModuleMessageType messageType) - { - DotNetNuke.UI.Skins.Skin.AddModuleMessage(this, messageHeader, message, messageType); - } - - protected T DataItem() - where T : class, new() - { - var t = this.Page.GetDataItem() as T ?? new T(); - return t; - } - - protected T DataValue() - { - return (T)this.Page.GetDataItem(); - } - - protected string DataValue(string format) - { - return string.Format(CultureInfo.CurrentCulture, format, this.DataValue()); + public void ShowMessage(string messageHeader, string message, ModuleMessage.ModuleMessageType messageType) + { + DotNetNuke.UI.Skins.Skin.AddModuleMessage(this, messageHeader, message, messageType); + } + + protected T DataItem() + where T : class, new() + { + var t = this.Page.GetDataItem() as T ?? new T(); + return t; + } + + protected T DataValue() + { + return (T)this.Page.GetDataItem(); + } + + protected string DataValue(string format) + { + return string.Format(CultureInfo.CurrentCulture, format, this.DataValue()); } /// - protected override void OnInit(EventArgs e) - { - PageViewHost.Register(this, this.Context, false); - - base.OnInit(e); - - this.Page.InitComplete += this.PageInitComplete; - this.Page.PreRenderComplete += this.PagePreRenderComplete; - this.Page.Load += this.PageLoad; - } - - private void PageInitComplete(object sender, EventArgs e) - { - if (this.Initialize != null) - { - this.Initialize(this, EventArgs.Empty); - } - } - - private void PageLoad(object sender, EventArgs e) - { - if (this.Load != null) - { - this.Load(this, e); - } - } - - private void PagePreRenderComplete(object sender, EventArgs e) - { - // This event is raised after any async page tasks have completed, so it - // is safe to data-bind - if (this.AutoDataBind) - { - this.DataBind(); - } - } - } -} + protected override void OnInit(EventArgs e) + { + PageViewHost.Register(this, this.Context, false); + + base.OnInit(e); + + this.Page.InitComplete += this.PageInitComplete; + this.Page.PreRenderComplete += this.PagePreRenderComplete; + this.Page.Load += this.PageLoad; + } + + private void PageInitComplete(object sender, EventArgs e) + { + if (this.Initialize != null) + { + this.Initialize(this, EventArgs.Empty); + } + } + + private void PageLoad(object sender, EventArgs e) + { + if (this.Load != null) + { + this.Load(this, e); + } + } + + private void PagePreRenderComplete(object sender, EventArgs e) + { + // This event is raised after any async page tasks have completed, so it + // is safe to data-bind + if (this.AutoDataBind) + { + this.DataBind(); + } + } + } +} diff --git a/DNN Platform/DotNetNuke.Web/Mvp/ModuleView{TModel}.cs b/DNN Platform/DotNetNuke.Web/Mvp/ModuleView{TModel}.cs index 87c397493a5..095ca5720b6 100644 --- a/DNN Platform/DotNetNuke.Web/Mvp/ModuleView{TModel}.cs +++ b/DNN Platform/DotNetNuke.Web/Mvp/ModuleView{TModel}.cs @@ -5,10 +5,12 @@ namespace DotNetNuke.Web.Mvp { using System; + using DotNetNuke.Internal.SourceGenerators; + using WebFormsMvp; - [Obsolete("Deprecated in DNN 9.2.0. Replace WebFormsMvp and DotNetNuke.Web.Mvp with MVC or SPA patterns instead. Scheduled removal in v11.0.0.")] - public abstract class ModuleView : ModuleViewBase, IView + [DnnDeprecated(9, 2, 0, "Replace WebFormsMvp and DotNetNuke.Web.Mvp with MVC or SPA patterns instead")] + public abstract partial class ModuleView : ModuleViewBase, IView where TModel : class, new() { private TModel model; diff --git a/DNN Platform/DotNetNuke.Web/Mvp/ProfileModuleViewBase.cs b/DNN Platform/DotNetNuke.Web/Mvp/ProfileModuleViewBase.cs index d578300a373..134d788bcbd 100644 --- a/DNN Platform/DotNetNuke.Web/Mvp/ProfileModuleViewBase.cs +++ b/DNN Platform/DotNetNuke.Web/Mvp/ProfileModuleViewBase.cs @@ -2,96 +2,97 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information -namespace DotNetNuke.Web.Mvp -{ - using System; - using System.Globalization; +namespace DotNetNuke.Web.Mvp +{ + using System; + using System.Globalization; - using DotNetNuke.Abstractions; - using DotNetNuke.Common; - using DotNetNuke.Common.Internal; - using DotNetNuke.Common.Utilities; - using DotNetNuke.Entities.Portals; - using DotNetNuke.Entities.Users; - using DotNetNuke.UI.Modules; - using Microsoft.Extensions.DependencyInjection; + using DotNetNuke.Abstractions; + using DotNetNuke.Common; + using DotNetNuke.Common.Internal; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Users; + using DotNetNuke.Internal.SourceGenerators; + using DotNetNuke.UI.Modules; + using Microsoft.Extensions.DependencyInjection; - [Obsolete("Deprecated in DNN 9.2.0. Replace WebFormsMvp and DotNetNuke.Web.Mvp with MVC or SPA patterns instead. Scheduled removal in v11.0.0.")] - public abstract class ProfileModuleViewBase : ModuleView, IProfileModule + [DnnDeprecated(9, 2, 0, "Replace WebFormsMvp and DotNetNuke.Web.Mvp with MVC or SPA patterns instead")] + public abstract partial class ProfileModuleViewBase : ModuleView, IProfileModule where TModel : class, new() { /// Initializes a new instance of the class. - public ProfileModuleViewBase() - { - this.NavigationManager = Globals.DependencyProvider.GetRequiredService(); + public ProfileModuleViewBase() + { + this.NavigationManager = Globals.DependencyProvider.GetRequiredService(); } /// public abstract bool DisplayModule { get; } /// - public int ProfileUserId - { - get - { - int userId = Null.NullInteger; - if (!string.IsNullOrEmpty(this.Request.Params["UserId"])) - { - userId = int.Parse(this.Request.Params["UserId"]); - } - - return userId; - } - } - - protected INavigationManager NavigationManager { get; } - - protected bool IsUser - { - get - { - return this.ProfileUserId == this.ModuleContext.PortalSettings.UserId; - } - } - - protected UserInfo ProfileUser - { - get { return UserController.GetUserById(this.ModuleContext.PortalId, this.ProfileUserId); } + public int ProfileUserId + { + get + { + int userId = Null.NullInteger; + if (!string.IsNullOrEmpty(this.Request.Params["UserId"])) + { + userId = int.Parse(this.Request.Params["UserId"]); + } + + return userId; + } + } + + protected INavigationManager NavigationManager { get; } + + protected bool IsUser + { + get + { + return this.ProfileUserId == this.ModuleContext.PortalSettings.UserId; + } + } + + protected UserInfo ProfileUser + { + get { return UserController.GetUserById(this.ModuleContext.PortalId, this.ProfileUserId); } } /// - protected override void OnInit(EventArgs e) - { - if (this.ProfileUserId == Null.NullInteger && - (this.ModuleContext.PortalSettings.ActiveTab.TabID == this.ModuleContext.PortalSettings.UserTabId - || this.ModuleContext.PortalSettings.ActiveTab.ParentId == this.ModuleContext.PortalSettings.UserTabId)) - { - // Clicked on breadcrumb - don't know which user - this.Response.Redirect( - this.Request.IsAuthenticated - ? this.NavigationManager.NavigateURL(this.ModuleContext.PortalSettings.ActiveTab.TabID, string.Empty, "UserId=" + this.ModuleContext.PortalSettings.UserId.ToString(CultureInfo.InvariantCulture)) - : this.GetRedirectUrl(), true); - } - - base.OnInit(e); - } - - private string GetRedirectUrl() - { - // redirect user to default page if not specific the home tab, do this action to prevent loop redirect. - var homeTabId = this.ModuleContext.PortalSettings.HomeTabId; - string redirectUrl; - - if (homeTabId > Null.NullInteger) - { - redirectUrl = TestableGlobals.Instance.NavigateURL(homeTabId); - } - else - { - redirectUrl = TestableGlobals.Instance.GetPortalDomainName(PortalSettings.Current.PortalAlias.HTTPAlias, this.Request, true) + "/" + Globals.glbDefaultPage; - } - - return redirectUrl; - } - } -} + protected override void OnInit(EventArgs e) + { + if (this.ProfileUserId == Null.NullInteger && + (this.ModuleContext.PortalSettings.ActiveTab.TabID == this.ModuleContext.PortalSettings.UserTabId + || this.ModuleContext.PortalSettings.ActiveTab.ParentId == this.ModuleContext.PortalSettings.UserTabId)) + { + // Clicked on breadcrumb - don't know which user + this.Response.Redirect( + this.Request.IsAuthenticated + ? this.NavigationManager.NavigateURL(this.ModuleContext.PortalSettings.ActiveTab.TabID, string.Empty, "UserId=" + this.ModuleContext.PortalSettings.UserId.ToString(CultureInfo.InvariantCulture)) + : this.GetRedirectUrl(), true); + } + + base.OnInit(e); + } + + private string GetRedirectUrl() + { + // redirect user to default page if not specific the home tab, do this action to prevent loop redirect. + var homeTabId = this.ModuleContext.PortalSettings.HomeTabId; + string redirectUrl; + + if (homeTabId > Null.NullInteger) + { + redirectUrl = TestableGlobals.Instance.NavigateURL(homeTabId); + } + else + { + redirectUrl = TestableGlobals.Instance.GetPortalDomainName(PortalSettings.Current.PortalAlias.HTTPAlias, this.Request, true) + "/" + Globals.glbDefaultPage; + } + + return redirectUrl; + } + } +} diff --git a/DNN Platform/DotNetNuke.Web/Mvp/SettingsModel.cs b/DNN Platform/DotNetNuke.Web/Mvp/SettingsModel.cs index 8ff9f5344c2..601d56473ab 100644 --- a/DNN Platform/DotNetNuke.Web/Mvp/SettingsModel.cs +++ b/DNN Platform/DotNetNuke.Web/Mvp/SettingsModel.cs @@ -2,16 +2,17 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information -namespace DotNetNuke.Web.Mvp -{ - using System; - using System.Collections.Generic; +namespace DotNetNuke.Web.Mvp +{ + using System.Collections.Generic; - [Obsolete("Deprecated in DNN 9.2.0. Replace WebFormsMvp and DotNetNuke.Web.Mvp with MVC or SPA patterns instead. Scheduled removal in v11.0.0.")] - public class SettingsModel - { - public Dictionary ModuleSettings { get; set; } - - public Dictionary TabModuleSettings { get; set; } - } -} + using DotNetNuke.Internal.SourceGenerators; + + [DnnDeprecated(9, 2, 0, "Replace WebFormsMvp and DotNetNuke.Web.Mvp with MVC or SPA patterns instead")] + public partial class SettingsModel + { + public Dictionary ModuleSettings { get; set; } + + public Dictionary TabModuleSettings { get; set; } + } +} diff --git a/DNN Platform/DotNetNuke.Web/Mvp/SettingsView.cs b/DNN Platform/DotNetNuke.Web/Mvp/SettingsView.cs index c237d098921..71e68fed2ae 100644 --- a/DNN Platform/DotNetNuke.Web/Mvp/SettingsView.cs +++ b/DNN Platform/DotNetNuke.Web/Mvp/SettingsView.cs @@ -2,25 +2,27 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information -namespace DotNetNuke.Web.Mvp -{ - using System; +namespace DotNetNuke.Web.Mvp +{ + using System; - [Obsolete("Deprecated in DNN 9.2.0. Replace WebFormsMvp and DotNetNuke.Web.Mvp with MVC or SPA patterns instead. Scheduled removal in v11.0.0.")] - public abstract class SettingsView : SettingsViewBase, ISettingsView + using DotNetNuke.Internal.SourceGenerators; + + [DnnDeprecated(9, 2, 0, "Replace WebFormsMvp and DotNetNuke.Web.Mvp with MVC or SPA patterns instead")] + public abstract partial class SettingsView : SettingsViewBase, ISettingsView where TModel : SettingsModel, new() - { + { private TModel model; /// - public TModel Model - { + public TModel Model + { get { - if (this.model == null) - { - throw new InvalidOperationException( - "The Model property is currently null, however it should have been automatically initialized by the presenter. This most likely indicates that no presenter was bound to the control. Check your presenter bindings."); + if (this.model == null) + { + throw new InvalidOperationException( + "The Model property is currently null, however it should have been automatically initialized by the presenter. This most likely indicates that no presenter was bound to the control. Check your presenter bindings."); } return this.model; @@ -30,30 +32,30 @@ public TModel Model { this.model = value; } - } - - protected string GetModuleSetting(string key, string defaultValue) - { - var value = defaultValue; - - if (this.Model.ModuleSettings.ContainsKey(key)) - { - value = this.Model.ModuleSettings[key]; - } - - return value; - } - - protected string GetTabModuleSetting(string key, string defaultValue) - { - var value = defaultValue; - - if (this.Model.TabModuleSettings.ContainsKey(key)) - { - value = this.Model.TabModuleSettings[key]; - } - - return value; - } - } -} + } + + protected string GetModuleSetting(string key, string defaultValue) + { + var value = defaultValue; + + if (this.Model.ModuleSettings.ContainsKey(key)) + { + value = this.Model.ModuleSettings[key]; + } + + return value; + } + + protected string GetTabModuleSetting(string key, string defaultValue) + { + var value = defaultValue; + + if (this.Model.TabModuleSettings.ContainsKey(key)) + { + value = this.Model.TabModuleSettings[key]; + } + + return value; + } + } +} diff --git a/DNN Platform/DotNetNuke.Web/Mvp/SettingsViewBase.cs b/DNN Platform/DotNetNuke.Web/Mvp/SettingsViewBase.cs index 6329574bbf2..4bc76fcdf05 100644 --- a/DNN Platform/DotNetNuke.Web/Mvp/SettingsViewBase.cs +++ b/DNN Platform/DotNetNuke.Web/Mvp/SettingsViewBase.cs @@ -1,14 +1,15 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information -namespace DotNetNuke.Web.Mvp -{ - using System; +namespace DotNetNuke.Web.Mvp +{ + using System; + using DotNetNuke.Internal.SourceGenerators; using DotNetNuke.UI.Modules; - [Obsolete("Deprecated in DNN 9.2.0. Replace WebFormsMvp and DotNetNuke.Web.Mvp with MVC or SPA patterns instead. Scheduled removal in v11.0.0.")] - public class SettingsViewBase : ModuleViewBase, ISettingsView, ISettingsControl + [DnnDeprecated(9, 2, 0, "Replace WebFormsMvp and DotNetNuke.Web.Mvp with MVC or SPA patterns instead")] + public partial class SettingsViewBase : ModuleViewBase, ISettingsView, ISettingsControl { /// public event EventHandler OnLoadSettings; @@ -17,35 +18,35 @@ public class SettingsViewBase : ModuleViewBase, ISettingsView, ISettingsControl public event EventHandler OnSaveSettings; /// - public void LoadSettings() - { - if (this.OnLoadSettings != null) - { - this.OnLoadSettings(this, EventArgs.Empty); - } - - this.OnSettingsLoaded(); + public void LoadSettings() + { + if (this.OnLoadSettings != null) + { + this.OnLoadSettings(this, EventArgs.Empty); + } + + this.OnSettingsLoaded(); } /// - public void UpdateSettings() - { - this.OnSavingSettings(); - - if (this.OnSaveSettings != null) - { - this.OnSaveSettings(this, EventArgs.Empty); - } - } - - /// The OnSettingsLoaded method is called when the Settings have been Loaded. - protected virtual void OnSettingsLoaded() - { - } - - /// OnSavingSettings method is called just before the Settings are saved. - protected virtual void OnSavingSettings() - { - } - } -} + public void UpdateSettings() + { + this.OnSavingSettings(); + + if (this.OnSaveSettings != null) + { + this.OnSaveSettings(this, EventArgs.Empty); + } + } + + /// The OnSettingsLoaded method is called when the Settings have been Loaded. + protected virtual void OnSettingsLoaded() + { + } + + /// OnSavingSettings method is called just before the Settings are saved. + protected virtual void OnSavingSettings() + { + } + } +} diff --git a/DNN Platform/DotNetNuke.Web/Mvp/ViewStateAttribute.cs b/DNN Platform/DotNetNuke.Web/Mvp/ViewStateAttribute.cs index 4143e17c668..c8c2d56ebc2 100644 --- a/DNN Platform/DotNetNuke.Web/Mvp/ViewStateAttribute.cs +++ b/DNN Platform/DotNetNuke.Web/Mvp/ViewStateAttribute.cs @@ -1,14 +1,16 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information -namespace DotNetNuke.Web.Mvp -{ +namespace DotNetNuke.Web.Mvp +{ using System; - [Obsolete("Deprecated in DNN 9.2.0. Replace WebFormsMvp and DotNetNuke.Web.Mvp with MVC or SPA patterns instead. Scheduled removal in v11.0.0.")] - [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false, Inherited = true)] - public class ViewStateAttribute : Attribute - { - public string ViewStateKey { get; set; } - } -} + using DotNetNuke.Internal.SourceGenerators; + + [DnnDeprecated(9, 2, 0, "Replace WebFormsMvp and DotNetNuke.Web.Mvp with MVC or SPA patterns instead")] + [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false, Inherited = true)] + public partial class ViewStateAttribute : Attribute + { + public string ViewStateKey { get; set; } + } +} diff --git a/DNN Platform/DotNetNuke.Web/Mvp/WebServicePresenter.cs b/DNN Platform/DotNetNuke.Web/Mvp/WebServicePresenter.cs index b2b464171d1..c17dca97827 100644 --- a/DNN Platform/DotNetNuke.Web/Mvp/WebServicePresenter.cs +++ b/DNN Platform/DotNetNuke.Web/Mvp/WebServicePresenter.cs @@ -2,21 +2,21 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information -namespace DotNetNuke.Web.Mvp -{ - using System; +namespace DotNetNuke.Web.Mvp +{ + using DotNetNuke.Internal.SourceGenerators; - using WebFormsMvp; + using WebFormsMvp; - [Obsolete("Deprecated in DNN 9.2.0. Replace WebFormsMvp and DotNetNuke.Web.Mvp with MVC or SPA patterns instead. Scheduled removal in v11.0.0.")] - public abstract class WebServicePresenter : Presenter + [DnnDeprecated(9, 2, 0, "Replace WebFormsMvp and DotNetNuke.Web.Mvp with MVC or SPA patterns instead")] + public abstract partial class WebServicePresenter : Presenter where TView : class, IWebServiceView { /// Initializes a new instance of the class. /// The view. - protected WebServicePresenter(TView view) - : base(view) - { - } - } -} + protected WebServicePresenter(TView view) + : base(view) + { + } + } +} diff --git a/DNN Platform/DotNetNuke.Web/Mvp/WebServiceView.cs b/DNN Platform/DotNetNuke.Web/Mvp/WebServiceView.cs index 9d0f10cab83..d140d88c35b 100644 --- a/DNN Platform/DotNetNuke.Web/Mvp/WebServiceView.cs +++ b/DNN Platform/DotNetNuke.Web/Mvp/WebServiceView.cs @@ -2,12 +2,12 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information -namespace DotNetNuke.Web.Mvp -{ - using System; +namespace DotNetNuke.Web.Mvp +{ + using DotNetNuke.Internal.SourceGenerators; - [Obsolete("Deprecated in DNN 9.2.0. Replace WebFormsMvp and DotNetNuke.Web.Mvp with MVC or SPA patterns instead. Scheduled removal in v11.0.0.")] - public abstract class WebServiceView : WebServiceViewBase + [DnnDeprecated(9, 2, 0, "Replace WebFormsMvp and DotNetNuke.Web.Mvp with MVC or SPA patterns instead")] + public abstract partial class WebServiceView : WebServiceViewBase { } -} +} diff --git a/DNN Platform/DotNetNuke.Web/Mvp/WebServiceViewBase.cs b/DNN Platform/DotNetNuke.Web/Mvp/WebServiceViewBase.cs index ec27d1c75d3..a6ab438f03c 100644 --- a/DNN Platform/DotNetNuke.Web/Mvp/WebServiceViewBase.cs +++ b/DNN Platform/DotNetNuke.Web/Mvp/WebServiceViewBase.cs @@ -2,14 +2,14 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information -namespace DotNetNuke.Web.Mvp -{ - using System; +namespace DotNetNuke.Web.Mvp +{ + using DotNetNuke.Internal.SourceGenerators; - using WebFormsMvp.Web; + using WebFormsMvp.Web; - [Obsolete("Deprecated in DNN 9.2.0. Replace WebFormsMvp and DotNetNuke.Web.Mvp with MVC or SPA patterns instead. Scheduled removal in v11.0.0.")] - public abstract class WebServiceViewBase : MvpWebService, IWebServiceViewBase + [DnnDeprecated(9, 2, 0, "Replace WebFormsMvp and DotNetNuke.Web.Mvp with MVC or SPA patterns instead")] + public abstract partial class WebServiceViewBase : MvpWebService, IWebServiceViewBase { } -} +} diff --git a/DNN Platform/DotNetNuke.Web/Mvp/WebServiceViewOfT.cs b/DNN Platform/DotNetNuke.Web/Mvp/WebServiceViewOfT.cs index 348bb532b2c..6f270e75cec 100644 --- a/DNN Platform/DotNetNuke.Web/Mvp/WebServiceViewOfT.cs +++ b/DNN Platform/DotNetNuke.Web/Mvp/WebServiceViewOfT.cs @@ -2,27 +2,29 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information -namespace DotNetNuke.Web.Mvp -{ - using System; +namespace DotNetNuke.Web.Mvp +{ + using System; - using WebFormsMvp; + using DotNetNuke.Internal.SourceGenerators; - [Obsolete("Deprecated in DNN 9.2.0. Replace WebFormsMvp and DotNetNuke.Web.Mvp with MVC or SPA patterns instead. Scheduled removal in v11.0.0.")] - public abstract class WebServiceViewOfT : ModuleViewBase, IView + using WebFormsMvp; + + [DnnDeprecated(9, 2, 0, "Replace WebFormsMvp and DotNetNuke.Web.Mvp with MVC or SPA patterns instead")] + public abstract partial class WebServiceViewOfT : ModuleViewBase, IView where TModel : class, new() - { + { private TModel model; /// - public TModel Model - { + public TModel Model + { get { - if (this.model == null) - { - throw new InvalidOperationException( - "The Model property is currently null, however it should have been automatically initialized by the presenter. This most likely indicates that no presenter was bound to the control. Check your presenter bindings."); + if (this.model == null) + { + throw new InvalidOperationException( + "The Model property is currently null, however it should have been automatically initialized by the presenter. This most likely indicates that no presenter was bound to the control. Check your presenter bindings."); } return this.model; @@ -32,6 +34,6 @@ public TModel Model { this.model = value; } - } - } -} + } + } +} diff --git a/DNN Platform/DotNetNuke.Web/UI/RibbonBarManager.cs b/DNN Platform/DotNetNuke.Web/UI/RibbonBarManager.cs index 59f74ce76a1..02f67c19e4c 100644 --- a/DNN Platform/DotNetNuke.Web/UI/RibbonBarManager.cs +++ b/DNN Platform/DotNetNuke.Web/UI/RibbonBarManager.cs @@ -44,7 +44,7 @@ public enum TabRelativeLocation CHILD = 3, } - public class RibbonBarManager + public partial class RibbonBarManager { private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(RibbonBarManager)); diff --git a/DNN Platform/DotNetNuke.Web/UI/Utilities.cs b/DNN Platform/DotNetNuke.Web/UI/Utilities.cs index 203dd96a8c2..6bf637faaa8 100644 --- a/DNN Platform/DotNetNuke.Web/UI/Utilities.cs +++ b/DNN Platform/DotNetNuke.Web/UI/Utilities.cs @@ -11,6 +11,7 @@ namespace DotNetNuke.Web.UI using System.Web.UI.WebControls; using DotNetNuke.Entities.Portals; + using DotNetNuke.Internal.SourceGenerators; using DotNetNuke.Services.Exceptions; using DotNetNuke.Services.Localization; using DotNetNuke.UI; @@ -19,7 +20,7 @@ namespace DotNetNuke.Web.UI using FileInfo = DotNetNuke.Services.FileSystem.FileInfo; - public class Utilities + public partial class Utilities { /// Applies a custom CSS file for a control using a consistent naming pattern. /// The control that should have a skin injected. @@ -30,20 +31,20 @@ public static void ApplyControlSkin(Control targetControl, string controlSubSkin ApplySkin(targetControl, string.Empty, controlName, controlSubSkinName); } - [Obsolete("Telerik support will be removed in DNN Platform 10.0.0. Please use one of the ApplyControlSkin overloads if applicable to your implementation.")] - public static void ApplySkin(Control targetControl) + [DnnDeprecated(9, 8, 0, "Telerik support will be removed in DNN Platform 10.0.0. Please use one of the ApplyControlSkin overloads if applicable to your implementation.", RemovalVersion = 10)] + public static partial void ApplySkin(Control targetControl) { ApplySkin(targetControl, string.Empty, string.Empty, string.Empty); } - [Obsolete("Telerik support will be removed in DNN Platform 10.0.0. Please use one of the ApplyControlSkin overloads if applicable to your implementation.")] - public static void ApplySkin(Control targetControl, string fallBackEmbeddedSkinName) + [DnnDeprecated(9, 8, 0, "Telerik support will be removed in DNN Platform 10.0.0. Please use one of the ApplyControlSkin overloads if applicable to your implementation.", RemovalVersion = 10)] + public static partial void ApplySkin(Control targetControl, string fallBackEmbeddedSkinName) { ApplySkin(targetControl, string.Empty, string.Empty, fallBackEmbeddedSkinName); } - [Obsolete("Telerik support will be removed in DNN Platform 10.0.0. Please use one of the ApplyControlSkin overloads if applicable to your implementation.")] - public static void ApplySkin(Control targetControl, string fallBackEmbeddedSkinName, string controlName) + [DnnDeprecated(9, 8, 0, "Telerik support will be removed in DNN Platform 10.0.0. Please use one of the ApplyControlSkin overloads if applicable to your implementation.", RemovalVersion = 10)] + public static partial void ApplySkin(Control targetControl, string fallBackEmbeddedSkinName, string controlName) { ApplySkin(targetControl, string.Empty, controlName, fallBackEmbeddedSkinName); } @@ -51,8 +52,8 @@ public static void ApplySkin(Control targetControl, string fallBackEmbeddedSkinN // Use selected skin's webcontrol skin if one exists // or use _default skin's webcontrol skin if one exists // or use embedded skin - [Obsolete("Telerik support will be removed in DNN Platform 10.0.0. Please use one of the ApplyControlSkin overloads if applicable to your implementation.")] - public static void ApplySkin(Control targetControl, string fallBackEmbeddedSkinName, string controlName, string webControlSkinSubFolderName) + [DnnDeprecated(9, 8, 0, "Telerik support will be removed in DNN Platform 10.0.0. Please use one of the ApplyControlSkin overloads if applicable to your implementation.", RemovalVersion = 10)] + public static partial void ApplySkin(Control targetControl, string fallBackEmbeddedSkinName, string controlName, string webControlSkinSubFolderName) { PropertyInfo skinProperty = null; PropertyInfo enableEmbeddedSkinsProperty = null; diff --git a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFormEditor.cs b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFormEditor.cs index 8702394a2ef..0ba3e9a539b 100644 --- a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFormEditor.cs +++ b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFormEditor.cs @@ -13,10 +13,11 @@ namespace DotNetNuke.Web.UI.WebControls using ClientDependency.Core; using DotNetNuke.Entities.Host; using DotNetNuke.Framework.JavaScriptLibraries; + using DotNetNuke.Internal.SourceGenerators; using DotNetNuke.Services.Localization; [ParseChildren(true)] - public class DnnFormEditor : WebControl, INamingContainer + public partial class DnnFormEditor : WebControl, INamingContainer { private object dataSource; private int itemCount; @@ -117,8 +118,8 @@ public override void DataBind() this.ChildControlsCreated = true; } - [Obsolete("Obsoleted in Platform 7.4.1, please add encryptIds. Scheduled removal in v10.0.0.")] - internal static void SetUpItems(IEnumerable items, WebControl parentControl, string localResourceFile) + [DnnDeprecated(7, 4, 1, "Please add encryptIds")] + internal static partial void SetUpItems(IEnumerable items, WebControl parentControl, string localResourceFile) { SetUpItems(items, parentControl, localResourceFile, false); } diff --git a/DNN Platform/DotNetNuke.Web/packages.config b/DNN Platform/DotNetNuke.Web/packages.config index d4b773bd198..1ee847145a7 100644 --- a/DNN Platform/DotNetNuke.Web/packages.config +++ b/DNN Platform/DotNetNuke.Web/packages.config @@ -13,7 +13,7 @@ - + \ No newline at end of file diff --git a/DNN Platform/DotNetNuke.WebUtility/DotNetNuke.WebUtility.vbproj b/DNN Platform/DotNetNuke.WebUtility/DotNetNuke.WebUtility.vbproj index d47e9619f1d..6a270285f6f 100644 --- a/DNN Platform/DotNetNuke.WebUtility/DotNetNuke.WebUtility.vbproj +++ b/DNN Platform/DotNetNuke.WebUtility/DotNetNuke.WebUtility.vbproj @@ -72,7 +72,7 @@ false false false - false + true 1 42016,42017,42018,42019,42032,42353,42354,42355 full @@ -92,7 +92,7 @@ true false false - false + true 1 42016,42017,42018,42019,42032,42353,42354,42355 pdbonly diff --git a/DNN Platform/HttpModules/Compression/CompressionModule.cs b/DNN Platform/HttpModules/Compression/CompressionModule.cs index cf48294f1b1..17f0c8d89e6 100644 --- a/DNN Platform/HttpModules/Compression/CompressionModule.cs +++ b/DNN Platform/HttpModules/Compression/CompressionModule.cs @@ -1,36 +1,37 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information -namespace DotNetNuke.HttpModules.Compression -{ - using System; - using System.IO; - using System.Web; +namespace DotNetNuke.HttpModules.Compression +{ + using System; + using System.IO; + using System.Web; - using DotNetNuke.Common.Utilities; - using DotNetNuke.Framework; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Framework; using DotNetNuke.Instrumentation; + using DotNetNuke.Internal.SourceGenerators; - [Obsolete("The http modules in web.config removed in 9.2.0, this class need to be removed in future release for upgrade compactible.. Scheduled removal in v11.0.0.")] - public class CompressionModule : IHttpModule - { - /// Init the handler and fulfill . - /// - /// This implementation hooks the ReleaseRequestState and PreSendRequestHeaders events to - /// figure out as late as possible if we should install the filter. Previous versions did - /// not do this as well. - /// - /// The this handler is working for. - public void Init(HttpApplication context) - { - } - - /// Implementation of . - /// - /// Currently empty. Nothing to really do, as I have no member variables. - /// - public void Dispose() - { - } - } -} + [DnnDeprecated(9, 2, 0, "No replacement")] + public partial class CompressionModule : IHttpModule + { + /// Init the handler and fulfill . + /// + /// This implementation hooks the ReleaseRequestState and PreSendRequestHeaders events to + /// figure out as late as possible if we should install the filter. Previous versions did + /// not do this as well. + /// + /// The this handler is working for. + public void Init(HttpApplication context) + { + } + + /// Implementation of . + /// + /// Currently empty. Nothing to really do, as I have no member variables. + /// + public void Dispose() + { + } + } +} diff --git a/DNN Platform/HttpModules/DotNetNuke.HttpModules.csproj b/DNN Platform/HttpModules/DotNetNuke.HttpModules.csproj index 2100ac876d7..a9f293bcdf1 100644 --- a/DNN Platform/HttpModules/DotNetNuke.HttpModules.csproj +++ b/DNN Platform/HttpModules/DotNetNuke.HttpModules.csproj @@ -44,8 +44,10 @@ full AllRules.ruleset 1591 - 7 + latest DEBUG + true + CS0618,SA1600,SA1601,SA1602,SA1608,SA1614 bin\ @@ -57,7 +59,9 @@ AllRules.ruleset 1591 true - 7 + latest + true + CS0618,SA1600,SA1601,SA1602,SA1608,SA1614 @@ -95,6 +99,10 @@ + + {5FE5D021-9C8D-47A6-BD34-F328BA3E709C} + DotNetNuke.Internal.SourceGenerators + {6928A9B1-F88A-4581-A132-D3EB38669BB0} DotNetNuke.Abstractions diff --git a/DNN Platform/HttpModules/Users Online/UsersOnlineModule.cs b/DNN Platform/HttpModules/Users Online/UsersOnlineModule.cs index 812c815d08d..566d5baf260 100644 --- a/DNN Platform/HttpModules/Users Online/UsersOnlineModule.cs +++ b/DNN Platform/HttpModules/Users Online/UsersOnlineModule.cs @@ -5,14 +5,14 @@ namespace DotNetNuke.HttpModules.UsersOnline { using System; using System.Web; - + using DotNetNuke.Common; - using DotNetNuke.Entities.Users; - - [Obsolete("Support for users online was removed in 8.x, other solutions exist outside of the DNN Platform. Scheduled removal in v11.0.0.")] - public class UsersOnlineModule : IHttpModule + using DotNetNuke.Entities.Users; + using DotNetNuke.Internal.SourceGenerators; + + [DnnDeprecated(8, 0, 0, "Other solutions exist outside of the DNN Platform", RemovalVersion = 11)] + public partial class UsersOnlineModule : IHttpModule { - [Obsolete("Support for users online was removed in 8.x, other solutions exist outside of the DNN Platform. Scheduled removal in v11.0.0.")] public string ModuleName { get @@ -27,12 +27,11 @@ public void Init(HttpApplication application) application.AuthorizeRequest += this.OnAuthorizeRequest; } - /// + /// public void Dispose() { } - [Obsolete("Support for users online was removed in 8.x, other solutions exist outside of the DNN Platform. Scheduled removal in v11.0.0.")] public void OnAuthorizeRequest(object s, EventArgs e) { // First check if we are upgrading/installing diff --git a/DNN Platform/JavaScript Libraries/DnnPlugins/DnnPlugins.dnn b/DNN Platform/JavaScript Libraries/DnnPlugins/DnnPlugins.dnn new file mode 100644 index 00000000000..c4ac3602a29 --- /dev/null +++ b/DNN Platform/JavaScript Libraries/DnnPlugins/DnnPlugins.dnn @@ -0,0 +1,40 @@ + + + + DNN jQuery Plugins + A collection of jQuery plugins for DNN UI components (tabs, panels, tooltips, checkboxes, etc.) + Icons\Sigma\Extensions_32x32_Standard.png + + .NET Foundation and Contributors + DNN Community + https://dnncommunity.org + info@dnncommunity.org + + + + true + + jQuery + jQuery-Migrate + jQuery-UI + HoverIntent + + + + + DnnPlugins + dnn.jquery.js + + + + + DnnPlugins + + dnn.jquery.js + + + + + + + diff --git a/DNN Platform/JavaScript Libraries/DnnPlugins/LICENSE.txt b/DNN Platform/JavaScript Libraries/DnnPlugins/LICENSE.txt new file mode 100644 index 00000000000..74e147f9f27 --- /dev/null +++ b/DNN Platform/JavaScript Libraries/DnnPlugins/LICENSE.txt @@ -0,0 +1,23 @@ +The MIT License (MIT) + +Copyright (c) .NET Foundation and Contributors +All Rights Reserved + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + diff --git a/DNN Platform/JavaScript Libraries/DnnPlugins/dnn.jquery.js b/DNN Platform/JavaScript Libraries/DnnPlugins/dnn.jquery.js new file mode 100644 index 00000000000..ba9dd2b5d35 --- /dev/null +++ b/DNN Platform/JavaScript Libraries/DnnPlugins/dnn.jquery.js @@ -0,0 +1,4323 @@ +(function ($) { + $.fn.dnnTabs = function (options) { + var opts = $.extend({}, $.fn.dnnTabs.defaultOptions, options), + $wrap = this; + + // patch for period in selector - http://jsfiddle.net/9Mst9/2/ + $.ui.tabs.prototype._sanitizeSelector = function (hash) { + return hash.replace(/:/g, "\\:").replace(/\./g, "\\\."); + }; + + $wrap.each(function () { + var showEvent, cookieId; + if (this.id) { + cookieId = 'dnnTabs-' + this.id; + if (opts.selected === -1) { + var cookieValue = dnn.dom.getCookie(cookieId); + if (cookieValue) { + opts.selected = cookieValue; + } + if (opts.selected === -1) { + opts.selected = 0; + } + } + showEvent = (function (cid) { + return function (event, ui) { + dnn.dom.setCookie(cid, ui.newTab.index(), opts.cookieDays, '/', '', false, opts.cookieMilleseconds); + }; + })(cookieId); + } else { + showEvent = function () { + }; + } + + $wrap.tabs({ + activate: showEvent, + active: opts.selected, + disabled: opts.disabled, + fx: { + opacity: opts.opacity, + duration: opts.duration + } + }); + + if (window.location.hash && window.location.hash != '#') { + var substr = window.location.hash.substr(0, 50); + $('a[href="' + encodeURI(substr) + '"]', $wrap).trigger('click'); + } + + // page validation integration - select tab that contain tripped validators + if (typeof window.Page_ClientValidate != "undefined" && $.isFunction(window.Page_ClientValidate)) { + $wrap.find(opts.validationTriggerSelector).click(function () { + if (!window.Page_ClientValidate(opts.validationGroup)) { + var invalidControl = $wrap.find(opts.invalidItemSelector).eq(0); + var $parent = invalidControl.closest(".ui-tabs-panel"); + if ($parent.length > 0) { + var tabId = $parent.attr("id"); + $parent.parent().find("a[href='#" + tabId + "']").click(); + } + } + }); + }; + }); + + return $wrap; + }; + + $.fn.dnnTabs.defaultOptions = { + opacity: 'toggle', + duration: 'fast', + validationTriggerSelector: '.dnnPrimaryAction', + validationGroup: '', + invalidItemSelector: '.dnnFormError[style*="inline"]', + regionToToggleSelector: 'fieldset', + selected: -1, + cookieDays: 0, + cookieMilleseconds: 1200000 // twenty minutes + }; + +})(jQuery); + +(function ($) { + $.fn.dnnConfirm = function (options) { + var opts = $.extend({}, $.fn.dnnConfirm.defaultOptions, options), + $wrap = this; + $wrap.each(function () { + var $this = $(this), + defaultAction = $this.attr('href'), + $dnnDialog; + + if (defaultAction || opts.isButton) { + $dnnDialog = $("
").html(opts.text).dialog(opts); + $dnnDialog.parent().find('.ui-dialog-titlebar-close').html('Close'); + $this.click(function (e, isTrigger) { + if (isTrigger) { + return true; + } + + if ($dnnDialog.is(':visible')) { + $dnnDialog.dialog("close"); + return true; + } + $dnnDialog.dialog({ + open: function () { + $('.ui-dialog-buttonpane').find('button:contains("' + opts.noText + '")').addClass('dnnConfirmCancel'); + }, + draggable: false, + buttons: [ + { + text: opts.yesText, + click: function () { + $dnnDialog.dialog("close"); + if ($.isFunction(opts.callbackTrue)) { + opts.callbackTrue.call(this); + } + else { + if (opts.isButton) { + $this.trigger("click", [true]); + } + else { + window.location.href = defaultAction; + } + } + }, + 'class': opts.buttonYesClass + }, + { + text: opts.noText, + click: function () { + $(this).dialog("close"); + if ($.isFunction(opts.callbackFalse)) { + opts.callbackFalse.call(this); + }; + }, + 'class': opts.buttonNoClass + } + ] + }); + + $dnnDialog.dialog('open'); + e.preventDefault(); + return false; + }); + } + }); + return $wrap; + }; + + $.fn.dnnConfirm.defaultOptions = { + text: 'Are you sure?', + yesText: 'Yes', + noText: 'No', + buttonYesClass: 'dnnPrimaryAction', + buttonNoClass: 'dnnSecondaryAction', + actionUrl: window.location.href, + autoOpen: false, + resizable: false, + modal: true, + title: 'Confirm', + dialogClass: 'dnnFormPopup dnnClear', + isButton: false + }; + +})(jQuery); + +(function($) { + if ($.dnnConfirm) return; + + $.dnnConfirm = function (opts) { + var defaultAction = opts.actionUrl ? opts.actionUrl : 'javascript:void(0);'; + var shadowLink = $(''); + shadowLink.dnnConfirm(opts).click(); + }; +})(jQuery); + +(function ($) { + $.dnnAlert = function (options) { + var opts = $.extend({}, $.dnnAlert.defaultOptions, options), + $dnnDialog = $("
").html(opts.text).dialog(opts); + + $dnnDialog.dialog({ + buttons: [ + { + text: opts.okText, + "class": opts.buttonOkClass, + click: function () { + $(this).dialog("close"); + if ($.isFunction(opts.callback)) { + opts.callback.call(this); + }; + return false; + } + } + ] + }); + $dnnDialog.dialog('open'); + }; + + $.dnnAlert.defaultOptions = { + okText: 'Ok', + autoOpen: false, + resizable: false, + modal: true, + buttonOkClass: 'dnnPrimaryAction', + dialogClass: 'dnnFormPopup dnnClear' + }; + +})(jQuery); + +(function ($) { + $.fn.dnnPanels = function (options) { + var opts = $.extend({}, $.fn.dnnPanels.defaultOptions, options), + $wrap = this; + + $wrap.each(function () { + var $this = $(this); + if (typeof (opts.onExpand) === "function") { + $this.on('onExpand', opts.onExpand); + } + if (typeof (opts.onHide) === "function") { + $this.on('onHide', opts.onHide); + } + // wire up click event to perform slide toggle + $this.find(opts.clickToToggleSelector).click(function (e) { + var toggle = $(this).toggleClass(opts.toggleClass).parent().next(opts.regionToToggleSelector).slideToggle(function () { + var visible = $(this).is(':visible'); + if (opts.saveState) { + var id = $(toggle).prev().attr("id"); + var cookieId = id ? id.replace(/[^a-zA-Z0-9\-]+/g, "") : ''; + if (cookieId) { + dnn.dom.setCookie(cookieId, visible, opts.cookieDays, '/', '', false, opts.cookieMilleseconds); + } + } + if (visible) { + $(this).trigger("onExpand"); + } + else { + $(this).trigger("onHide"); + } + }); + + e.preventDefault(); + e.stopImmediatePropagation(); + return false; + }); + + function collapsePanel($clicker, $region) { + $clicker.removeClass(opts.toggleClass); + $region.hide(); + $this.trigger("onHide"); + } + + function expandPanel($clicker, $region) { + $clicker.addClass(opts.toggleClass); + $region.show(); + $this.trigger("onExpand"); + } + + // walk over each selector and expand or collapse as necessary + $this.find(opts.sectionHeadSelector).each(function (indexInArray, valueOfElement) { + var $self = $(valueOfElement), + elementId = $self.attr("id"), + cookieId = elementId ? elementId.replace(/[^a-zA-Z0-9\-]+/g, "") : '', + cookieValue = cookieId ? dnn.dom.getCookie(cookieId) : '', + $clicker = $self.find(opts.clickToToggleIsolatedSelector), + $region = $self.next(opts.regionToToggleSelector), + $parentSeparator = $self.parents(opts.panelSeparatorSelector), + groupPanelIndex = $parentSeparator.find(opts.sectionHeadSelector).index($self); + + // default value + var isOpen = false; + if ((indexInArray === 0 && opts.defaultState == "first") || // cookie set to true OR first panel + ($parentSeparator.length > 0 && groupPanelIndex === 0 && opts.defaultState == "first") || // grouping is used & its the first panel in its group + (opts.defaultState == "open")) // default open + { + isOpen = true; + } + if (opts.saveState) { + if (cookieValue == "true") { + isOpen = true; + } + else if (cookieValue == "false") { + isOpen = false; + } + } + + if (isOpen) { + expandPanel($clicker, $region); + } + else { + collapsePanel($clicker, $region); + } + }); + + // page validation integration - expand collapsed panels that contain tripped validators + $this.find(opts.validationTriggerSelector).click(function () { + if (typeof window.Page_ClientValidate != "undefined" && $.isFunction(window.Page_ClientValidate)) { + if (!window.Page_ClientValidate(opts.validationGroup)) { + $this.find(opts.invalidItemSelector).each(function () { + var $parent = $(this).closest(opts.regionToToggleSelector); + if ($parent.is(':hidden')) { + $parent.prev(opts.sectionHeadSelector).find(opts.clickToToggleIsolatedSelector).click(); + } + }); + } + } + }); + }); + return $wrap; + }; + + $.fn.dnnPanels.defaultOptions = { + clickToToggleSelector: 'h2.dnnFormSectionHead a', + sectionHeadSelector: '.dnnFormSectionHead', + regionToToggleSelector: 'fieldset', + toggleClass: 'dnnSectionExpanded', + clickToToggleIsolatedSelector: 'a', + validationTriggerSelector: '.dnnPrimaryAction', + invalidItemSelector: '.dnnFormError[style*="inline"]', + validationGroup: '', + panelSeparatorSelector: '.ui-tabs-panel', + cookieDays: 0, + cookieMilleseconds: 1200000, // twenty minutes + saveState: true, + defaultState: 'first' // open | closed | first + }; + +})(jQuery); + +(function ($) { + $.fn.dnnPreview = function (options) { + var opts = $.extend({}, $.fn.dnnPreview.defaultOptions, options), + $wrap = this; + + $wrap.each(function () { + var $this = $(this); + $this.find(opts.linkSelector).click(function (e) { + e.preventDefault(); + var params = "?"; + var skin, container; + + if (opts.useComboBox) { + var skinComboBox = $('#' + opts.skinSelector); + var containerComboBox = $('#' + opts.containerSelector);; + + skin = skinComboBox.length ? skinComboBox[0].selectize.getValue() : ''; + container = containerComboBox.length ? containerComboBox[0].selectize.getValue() : ''; + } + else { + skin = $this.find(opts.skinSelector).val(); + container = $this.find(opts.containerSelector).val(); + } + if (skin) { + params += "SkinSrc=" + skin; + } + if (container) { + if (skin) { + params += "&"; + } + params += "ContainerSrc=" + container; + } + if (opts.ModuleId) { + if (params !== "?") { + params += "&ModuleID=" + opts.ModuleId; + } else { + params += "ModuleID=" + opts.ModuleId; + } + } + if (params != "?") { + window.open(encodeURI(opts.baseUrl + params.replace(/.ascx/gi, '')), "skinpreview"); + } + else { + $.dnnAlert({ text: opts.noSelectionMessage, okText: opts.alertOkText, closeText: opts.alertCloseText }); + } + }); + }); + + return $wrap; + }; + + $.fn.dnnPreview.defaultOptions = { + baseUrl: window.location.protocol + "//" + window.location.host + window.location.pathname, + linkSelector: 'a.dnnSecondaryAction', + skinSelector: '', + containerSelector: '', + noSelectionMessage: 'Please select a preview option.', + alertOkText: 'Ok', + alertCloseText: 'close', + useComboBox: false + }; + +})(jQuery); + +(function ($) { + $.fn.dnnExpandAll = function (options) { + var opts = $.extend({}, $.fn.dnnExpandAll.defaultOptions, options), + $elem = this; + + if (($(opts.targetArea).find(opts.targetSelector + ':visible').length === + $(opts.targetArea).find(opts.targetSelector + opts.targetExpandedSelector + ':visible').length) + && !$(this).hasClass('expanded')) { + $(this).addClass('expanded').text(opts.collapseText); + } + + $elem.click(function (e) { + e.preventDefault(); + var $this = $(this); + if ($this.hasClass('expanded')) { + $this.removeClass('expanded').text(opts.expandText); + $(opts.targetArea).find(opts.targetSelector + opts.targetExpandedSelector + ':visible').click(); + } + else { + $this.addClass('expanded').text(opts.collapseText); + $(opts.targetArea).find(opts.targetSelector + ':visible').not(opts.targetExpandedSelector).click(); + } + + //stop event from called again + e.stopImmediatePropagation(); + }); + + return $elem; + }; + $.fn.dnnExpandAll.defaultOptions = { + expandText: 'Expand All', + collapseText: 'Collapse All', + targetArea: '#dnnHostSettings', + targetSelector: 'h2.dnnFormSectionHead a', + targetExpandedSelector: '.dnnSectionExpanded' + }; +})(jQuery); + +(function ($) { + $.fn.dnnTooltip = function (options) { + var opts = $.extend({}, $.fn.dnnTooltip.defaultOptions, options), + $wrap = this; + + $wrap.each(function () { + var $this = $(this), + dnnFormHelp = $this.prev(); + if ($this.data('initialized')) return; + dnnFormHelp.on('click', function (e) { + e.preventDefault(); + }); + var helpSelector = $this.find(opts.helpSelector); + $this.parent().css({ position: 'relative' }); + $this.css({ position: 'absolute', right: '-29%' }); + var hoverOnToolTip = false, hoverOnPd = false; + + dnnFormHelp.hoverIntent({ + over: function () { + hoverOnPd = true; + var tooltipHeight = helpSelector.height(); + var top = -(tooltipHeight + 30); + if ((tooltipHeight + 30) <= $this.parent().offset().top) { + helpSelector.parent().css({ top: top + 'px' }); + $this.find("div.dnnFormHelpContent span").addClass("bottomArrow"); + $this.find("div.dnnFormHelpContent span").removeClass("topArrow"); + + } else { + helpSelector.parent().css({ top: 30 + 'px' }); + $this.find("div.dnnFormHelpContent span").addClass("topArrow"); + $this.find("div.dnnFormHelpContent span").removeClass("bottomArrow"); + } + helpSelector.css('visibility', 'visible'); + }, + out: function () { + hoverOnPd = false; + if (!$this.hasClass(opts.pinnedClass) && !hoverOnToolTip) { + helpSelector.css('visibility', 'hidden'); + } + }, + timeout: 200, + interval: 200 + }); + + helpSelector.hover(function () { hoverOnToolTip = true; }, function () { + hoverOnToolTip = false; + if (!$this.hasClass(opts.pinnedClass) && !hoverOnPd) { + helpSelector.css('visibility', 'hidden'); + } + }); + + var pinHelper = helpSelector.find(opts.pinSelector); + + pinHelper.on('click', function (e) { + e.preventDefault(); + if ($this.hasClass(opts.pinnedClass)) { + helpSelector.css({ "left": '0', "top": '0' }) + .css('visibility', 'hidden') + .draggable('destroy'); + $this.removeClass(opts.pinnedClass); + } + else { + + $this.addClass(opts.pinnedClass); + if ($.isFunction($().draggable)) { + helpSelector.draggable(); + } + } + }); + + $this.data('initialized', 1); + }); + + return $wrap; + }; + + $.fn.dnnTooltip.defaultOptions = { + pinSelector: 'a.pinHelp', + helpSelector: '.dnnFormHelpContent', + pinnedClass: 'dnnTooltipPinned' + }; + +})(jQuery); + +(function ($) { + var cb = function (e) { + if (!e) e = window.event; + e.cancelBubble = true; + if (e.stopPropagation) e.stopPropagation(); + }; + + /* DNN customized checkbox/radiobox */ + $.fn.dnnCheckbox = function (options) { + var settings = { + cls: 'dnnCheckbox' /* checkbox */ + , labelClass: 'dnnBoxLabel' + }; + settings = $.extend(settings, options || {}); + + var addEvents = function (object) { + var checked = object.checked, + disabled = object.disabled, + $object = $(object); + + if (object.stateInterval) + clearInterval(object.stateInterval); + + object.stateInterval = setInterval( + function () { + if (object.disabled != disabled) + $object.trigger((disabled = !!object.disabled) ? 'disable' : 'enable'); + if (object.checked != checked) + $object.trigger((checked = !!object.checked) ? 'check' : 'uncheck'); + }, + 10 /* in miliseconds.*/ + ); + return $object; + }; + + return this.each(function () { + var ch = this; + + if ($(ch).data("checkBoxWrapped")) { + return; + } + $(ch).data("checkBoxWrapped", true); + + if ($(this).hasClass('normalCheckBox') || $(this).hasClass('normalRadioButton')) return; + var parentCheckBoxHolder = $(this).closest('.normalCheckBox'); + var parentRadioButtonHolder = $(this).closest('.normalRadioButton'); + if (parentCheckBoxHolder.length || parentRadioButtonHolder.length) return; + var $ch = addEvents(ch); + if (ch.wrapper) ch.wrapper.remove(); + ch.wrapper = $('checkbox'); + ch.wrapperInner = ch.wrapper.children('span:eq(0)'); + ch.wrapper.hover( + function (e) { ch.wrapperInner.addClass(settings.cls + '-hover'); cb(e); }, + function (e) { ch.wrapperInner.removeClass(settings.cls + '-hover'); cb(e); } + ); + + $ch.css({ position: 'absolute', zIndex: -1, opacity: 0 }).after(ch.wrapper); + + var label, parentLabel = false; + label = $ch.closest('label'); + if (!label.length) + label = false; + else + parentLabel = true; + + if (!label && $ch.attr('id')) { + label = $('label[for="' + $ch.attr('id') + '"]'); + if (!label.length) label = false; + } + + if (label) { + label.addClass(settings.labelClass); + if (!parentLabel) { + label.click(function (e) { + clickHandler(e); + return false; + }); + } + else { + label.children().each(function () { + var $this = $(this); + if ($this.is('input')) return; + + $this.click(function (e) { + clickHandler(e); + return false; + }); + }); + } + } + + if (!parentLabel) { + ch.wrapper.click(function (e) { + clickHandler(e); + return false; + }); + } + + function clickHandler(e) { + if (ch.disabled) { + return; + } + $ch.triggerHandler('focus'); + var previousChecked = ch.checked; + ch.click(); + if (ch.checked == previousChecked && ch.type == 'checkbox') { + ch.checked = !ch.checked; //Fix for Firefox browser + } + $ch.trigger('change', [e]); + cb(e); + } + + $ch.on('disable', function () { ch.wrapperInner.addClass(settings.cls + '-disabled'); }).on('enable', function () { ch.wrapperInner.removeClass(settings.cls + '-disabled'); }); + $ch.on('check', function () { ch.wrapper.addClass(settings.cls + '-checked'); }).on('uncheck', function () { ch.wrapper.removeClass(settings.cls + '-checked'); }); + $ch.on('focus', function (e) { if (!e.isTrigger) ch.wrapper.addClass(settings.cls + '-focus'); }).on('blur', function () { ch.wrapper.removeClass(settings.cls + '-focus'); }); + + /* Applying checkbox state */ + if (ch.checked) + ch.wrapper.addClass(settings.cls + '-checked'); + if (ch.disabled) + ch.wrapperInner.addClass(settings.cls + '-disabled'); + + }); + }; + + $.fn.dnnHelperTipDestroy = function () { + return this.each(function () { + var pd = this; + if (pd.id) { + $('div[data-tipholder="' + pd.id + '"]').remove(); + } + }); + }; + + $.fn.dnnHelperTip = function (options) { + var settings = { + cls: 'dnnHelperTip', + helpContent: "This is hover helper tooltip", + holderId: '', + show: false // immediately show tooltip after call + }; + settings = $.extend(settings, options || {}); + return this.each(function () { + var pd = this, + $pd = $(this); + if (pd.tooltipWrapper) pd.tooltipWrapper.remove(); + + pd.tooltipWrapper = $('
' + settings.helpContent + '
'); + $('body').append(pd.tooltipWrapper); + pd.tooltipWrapper.css({ position: 'absolute' }); + pd.tooltipWrapperInner = $('.dnnFormHelpContent', pd.tooltipWrapper); + + var tooltipHeight = pd.tooltipWrapperInner.height(); + pd.tooltipWrapperInner.css({ left: '-10px', top: -(tooltipHeight + 30) + 'px' }); + var hoverOnPd = false; + $pd.hover( + function () { + hoverOnPd = true; + setTimeout(function () { + if (hoverOnPd) + pd.tooltipWrapperInner.css('visibility', 'visible'); + }, 400); + }, + function () { + hoverOnPd = false; + setTimeout(function () { + if (!hoverOnPd) + pd.tooltipWrapperInner.css('visibility', 'hidden'); + }, 400); + + }); + + if (settings.show) { + hoverOnPd = true; + setTimeout(function () { + pd.tooltipWrapperInner.css('visibility', 'visible'); + }, 400); + } + + $pd.on('mousemove', function (e) { + var x = e.pageX; var y = e.pageY; + var pos = $('body').css('position'); + if (pos == 'relative') y -= 38; + pd.tooltipWrapper.css({ left: x + 'px', top: y + 'px', 'z-index': '99999' }); + }); + }); + }; + + $.fn.dnnProgressbar = function () { + var $pd = $(this), + pd = this; + + if (pd.tooltipWrapper) pd.tooltipWrapper.remove(); + pd.tooltipWrapper = $('
').insertAfter($pd); + pd.tooltipWrapperInner = $('.dnnFormHelpContent', pd.tooltipWrapper); + pd.tooltipWrapperInner.css({ width: '32px', padding: '7px' }); + $pd.parent().css({ position: 'relative' }); + + var hoverOnToolTip = false, hoverOnPd = false; + $pd.hoverIntent({ + over: function () { + hoverOnPd = true; + var val = $(this).children(':first').progressbar('value'); + pd.update(val); + pd.tooltipWrapperInner.css('visibility', 'visible'); + + }, + out: function () { + hoverOnPd = false; + if (!hoverOnToolTip) { + pd.tooltipWrapperInner.css('visibility', 'hidden'); + } + }, + timeout: 200, + interval: 200 + }); + + pd.tooltipWrapperInner.hover(function () { hoverOnToolTip = true; }, function () { + hoverOnToolTip = false; + if (!hoverOnPd) { + pd.tooltipWrapperInner.hide(); + } + }); + + pd.update = function (value) { + pd.tooltipWrapperInner.find('span').html(value + ' %'); + var pdTop = $pd.position().top, + tooltipHeight = pd.tooltipWrapperInner.height(); + + pdTop -= (tooltipHeight + 10); + var pdLeft = value > 50 ? (value - 4) + '%' : value > 0 ? (value - 2) + '%' : '10px'; + pd.tooltipWrapper.css({ position: 'absolute', left: pdLeft, top: pdTop + 'px' }); + }; + + return this; + }; + + $.fn.dnnSpinner = function (options) { + var opt = $.extend({ + type: 'range', + typedata: '', + width: '150px', + looping: false + }, options); + + var otypedata; + + if (options != null && options.typedata != null) { + otypedata = $.extend({ + min: 1, + max: 10, + interval: 1, + decimalplaces: 0 + }, options.typedata); + } + else { + otypedata = $.extend({ + min: 1, + max: 10, + interval: 1, + decimalplaces: 0 + }); + } + opt.typedata = otypedata; + + var inputControl = this; + if (!inputControl.is(':text')) + return inputControl; + + if (inputControl.hasClass('dnnSpinnerInput')) { + return inputControl; + } + else { + inputControl.addClass('dnnSpinnerInput'); + } + + var strContainerDiv = ''; + strContainerDiv += '
'; + strContainerDiv += '
'; + strContainerDiv += '
'; + strContainerDiv += ''; + strContainerDiv += ''; + strContainerDiv += '
'; + var objContainerDiv = $(strContainerDiv).insertAfter(inputControl); + inputControl.insertAfter($("div.dnnSpinnerDisplay", objContainerDiv)); + $("div.dnnSpinnerDisplay", objContainerDiv).click(function () { + if (opt.type == 'range') { + var displayCtrl = $(this); + var innerInput = $('input[type="text"]', displayCtrl); + if (innerInput.length < 1) { + var originalVal = displayCtrl.html(); + innerInput = $('').val(originalVal); + displayCtrl.html(innerInput); + innerInput.blur(function () { + var newVal = $(this).val(); + if (newVal > opt.typedata.max) { + newVal = opt.typedata.max; + } + if (newVal < opt.typedata.min) { + newVal = opt.typedata.min; + } + $(this).remove(); + selectedValue = parseInt(newVal); + inputControl.val(newVal); + displayCtrl.html(newVal); + }).keypress(function (e) { + var regex = new RegExp("^[0-9]+$"); + var key = String.fromCharCode(!e.charCode ? e.which : e.charCode); + if (!regex.test(key)) { + event.preventDefault(); + return false; + } + return true; + }); + } + innerInput.focus(); + } + + inputControl.triggerHandler('focus'); + }); + inputControl.css('display', 'none'); + + switch (opt.type) { + case 'range': + if (opt.defaultVal < opt.typedata.min || opt.defaultVal > opt.typedata.max) { + opt.defaultVal = opt.typedata.min; + } + if (opt.defaultVal % opt.typedata.interval > 0) { + opt.defaultVal = parseInt((opt.defaultVal / opt.typedata.interval).toFixed(0)) * opt.typedata.interval; + } + inputControl.val(opt.defaultVal.toFixed(opt.typedata.decimalplaces)); + ($("div.dnnSpinnerDisplay", objContainerDiv)).html(opt.defaultVal.toFixed(opt.typedata.decimalplaces)); + var selectedValue = opt.defaultVal; + if ((opt.typedata.max - opt.typedata.min) > opt.typedata.interval) { + $("a.dnnSpinnerTopButton", objContainerDiv).click(function () { + + if ((selectedValue + opt.typedata.interval) <= opt.typedata.max || opt.looping) { + if ((selectedValue + opt.typedata.interval) > opt.typedata.max) { + selectedValue = opt.typedata.min - opt.typedata.interval; + } + var valueData = (selectedValue + opt.typedata.interval).toFixed(opt.typedata.decimalplaces); + selectedValue += opt.typedata.interval; + ($("div.dnnSpinnerDisplay", objContainerDiv)).html(valueData); + inputControl.val(valueData); + } + inputControl.triggerHandler('focus'); + return false; + }); + + $("a.dnnSpinnerBotButton", objContainerDiv).click(function () { + if ((selectedValue - opt.typedata.interval) >= opt.typedata.min || opt.looping) { + if ((selectedValue - opt.typedata.interval) < opt.typedata.min) { + selectedValue = opt.typedata.max + opt.typedata.interval; + } + var valueData = (selectedValue - opt.typedata.interval).toFixed(opt.typedata.decimalplaces); + selectedValue -= opt.typedata.interval; + ($("div.dnnSpinnerDisplay", objContainerDiv)).html(valueData); + inputControl.val(valueData); + } + inputControl.triggerHandler('focus'); + return false; + }); + } + + break; + case 'list': + if (!opt.typedata.list || opt.typedata.list.lenght == 0) { + return inputControl; + } + + var listItems = opt.typedata.list.split(','); + var selectedIndex = jQuery.inArray(opt.defaultVal, listItems); + if (selectedIndex < 0) { + selectedIndex = 0; + opt.defaultVal = listItems[0]; + } + + inputControl.val(opt.defaultVal); + ($("div.dnnSpinnerDisplay", objContainerDiv)).html(opt.defaultVal); + + if (listItems.length > 1) { + // attach events; + $("a.dnnSpinnerBotButton", objContainerDiv).click(function () { + if (selectedIndex < (listItems.length - 1) || opt.looping) { + if (selectedIndex == listItems.length - 1) { + selectedIndex = -1; + } + selectedIndex++; + var valueData = listItems[selectedIndex]; + ($("div.dnnSpinnerDisplay", objContainerDiv)).html(valueData); + inputControl.val(valueData); + } + inputControl.triggerHandler('focus'); + return false; + }); + + $("a.dnnSpinnerTopButton", objContainerDiv).click(function () { + if (selectedIndex > 0 || opt.looping) { + if (selectedIndex == 0) { + selectedIndex = listItems.length; + } + selectedIndex--; + var valueData = listItems[selectedIndex]; + ($("div.dnnSpinnerDisplay", objContainerDiv)).html(valueData); + inputControl.val(valueData); + } + inputControl.triggerHandler('focus'); + return false; + }); + } + + break; + }; + return inputControl; + }; +})(jQuery); + +(function ($) { + $.fn.dnnAutocomplete = function (options) { + var url; + if (arguments.length > 1) { + url = options; + options = arguments[1]; + options.url = url; + } else if (typeof options === 'string') { + url = options; + options = { url: url }; + } + var opts = $.extend({}, $.fn.dnnAutocomplete.defaults, options); + return this.each(function () { + var $this = $(this); + $this.data('autocompleter', new $.dnnAutocompleter( + $this, + $.meta ? $.extend({}, opts, $this.data()) : opts + )); + }); + }; + + $.fn.dnnAutocomplete.defaults = { + inputClass: 'dnn_acInput', + loadingClass: 'dnn_acLoading', + resultsClass: 'dnn_acResults', + selectClass: 'dnn_acSelect', + queryParamName: 'q', + contentTypeParamName: 'contentTypeId', + extraParams: {}, + remoteDataType: false, + lineSeparator: '\n', + cellSeparator: '|', + minChars: 2, + maxItemsToShow: 10, + delay: 400, + useCache: false, + maxCacheLength: 10, + matchSubset: true, + matchCase: false, + matchInside: true, + mustMatch: false, + selectFirst: false, + selectOnly: false, + showResult: null, + preventDefaultReturn: 1, + preventDefaultTab: 0, + autoFill: false, + filterResults: true, + sortResults: true, + sortFunction: null, + onItemSelect: null, + onNoMatch: null, + onFinish: null, + matchStringConverter: null, + beforeUseConverter: null, + autoWidth: 'min-width', + useDelimiter: false, + delimiterChar: ',', + delimiterKeyCode: 188, + processData: null, + onError: null, + moduleId: null // dnn Module Id context if needed + }; + + var sanitizeResult = function (result) { + var value, data; + var type = typeof result; + if (type === 'string') { + value = result; + data = {}; + } else if ($.isArray(result)) { + value = result[0]; + data = result.slice(1); + } else if (type === 'object') { + value = result.value; + data = result.data; + } else value = ''; + value = String(value); + if (typeof data !== 'object') { + data = {}; + } + return { + value: value, + data: data + }; + }; + + var sanitizeInteger = function (value, stdValue, options) { + var num = parseInt(value, 10); + options = options || {}; + if (isNaN(num) || (options.min && num < options.min)) { + num = stdValue; + } + return num; + }; + + var makeUrlParam = function (name, value) { + return [name, encodeURIComponent(value)].join('='); + }; + + var makeUrl = function (url, params) { + var urlAppend = []; + $.each(params, function (index, value) { + urlAppend.push(makeUrlParam(index, value)); + }); + if (urlAppend.length) { + url += url.indexOf('?') === -1 ? '?' : '&'; + url += urlAppend.join('&'); + } + return url; + }; + + var sortValueAlpha = function (a, b, matchCase) { + a = String(a.value); + b = String(b.value); + if (!matchCase) { + a = a.toLowerCase(); + b = b.toLowerCase(); + } + if (a > b) { + return 1; + } + if (a < b) { + return -1; + } + return 0; + }; + + $.dnnAutocompleter = function ($elem, options) { + + if (!$elem || !($elem instanceof $) || $elem.length !== 1 || $elem.get(0).tagName.toUpperCase() !== 'INPUT') { + throw new Error('Invalid parameter for dnnAutocompleter, jQuery object with one element with INPUT tag expected.'); + } + + var self = this; + this.options = options; + this.cacheData_ = {}; + this.cacheLength_ = 0; + this.selectClass_ = 'jquery-autocomplete-selected-item'; + this.keyTimeout_ = null; + this.finishTimeout_ = null; + this.lastKeyPressed_ = null; + this.lastProcessedValue_ = null; + this.lastSelectedValue_ = null; + this.active_ = false; + this.finishOnBlur_ = true; + + this.options.minChars = sanitizeInteger(this.options.minChars, $.fn.dnnAutocomplete.defaults.minChars, { min: 0 }); + this.options.maxItemsToShow = sanitizeInteger(this.options.maxItemsToShow, $.fn.dnnAutocomplete.defaults.maxItemsToShow, { min: 0 }); + this.options.maxCacheLength = sanitizeInteger(this.options.maxCacheLength, $.fn.dnnAutocomplete.defaults.maxCacheLength, { min: 1 }); + this.options.delay = sanitizeInteger(this.options.delay, $.fn.dnnAutocomplete.defaults.delay, { min: 0 }); + if (this.options.preventDefaultReturn != 2) { + this.options.preventDefaultReturn = this.options.preventDefaultReturn ? 1 : 0; + } + if (this.options.preventDefaultTab != 2) { + this.options.preventDefaultTab = this.options.preventDefaultTab ? 1 : 0; + } + + this.dom = {}; + this.dom.$elem = $elem; + this.dom.$elem.attr('autocomplete', 'off').addClass(this.options.inputClass); + this.dom.$results = $('
').hide().addClass(this.options.resultsClass).css({ + position: 'absolute' + }); + $('body').append(this.dom.$results); + $elem.keydown(function (e) { + self.lastKeyPressed_ = e.keyCode; + switch (self.lastKeyPressed_) { + case self.options.delimiterKeyCode: // comma = 188 + if (self.options.useDelimiter && self.active_) { + self.selectCurrent(); + } + break; + + // ignore navigational & special keys + case 35: // end + case 36: // home + case 16: // shift + case 17: // ctrl + case 18: // alt + case 37: // left + case 39: // right + break; + + case 38: // up + e.preventDefault(); + if (self.active_) { + self.focusPrev(); + } else { + self.activate(); + } + return false; + + case 40: // down + e.preventDefault(); + if (self.active_) { + self.focusNext(); + } else { + self.activate(); + } + return false; + + case 9: // tab + if (self.active_) { + self.selectCurrent(); + if (self.options.preventDefaultTab) { + e.preventDefault(); + return false; + } + } + if (self.options.preventDefaultTab === 2) { + e.preventDefault(); + return false; + } + break; + + case 13: // return + if (self.active_) { + self.selectCurrent(); + if (self.options.preventDefaultReturn) { + e.preventDefault(); + return false; + } + } + if (self.options.preventDefaultReturn === 2) { + e.preventDefault(); + return false; + } + break; + + case 27: // escape + if (self.active_) { + e.preventDefault(); + self.deactivate(true); + return false; + } + break; + + default: + self.activate(); + + } + return true; + }); + + var onBlurFunction = function () { + self.deactivate(true); + }; + $elem.blur(function () { + if (self.finishOnBlur_) { + self.finishTimeout_ = setTimeout(onBlurFunction, 1000); + } + }); + + $elem.parents('form').on('submit', onBlurFunction); + + }; + + $.dnnAutocompleter.prototype.position = function () { + var offset = this.dom.$elem.offset(); + var height = this.dom.$results.outerHeight(); + var totalHeight = window.outerHeight; + var inputBottom = offset.top + this.dom.$elem.outerHeight(); + var bottomIfDown = inputBottom + height; + // Set autocomplete results at the bottom of input + var position = { top: inputBottom, left: offset.left }; + if (bottomIfDown > totalHeight) { + // Try to set autocomplete results at the top of input + var topIfUp = offset.top - height; + if (topIfUp >= 0) { + position.top = topIfUp; + } + } + this.dom.$results.css(position); + }; + + $.dnnAutocompleter.prototype.cacheRead = function (filter) { + var filterLength, searchLength, search, maxPos, pos; + if (this.options.useCache) { + filter = String(filter); + filterLength = filter.length; + if (this.options.matchSubset) { + searchLength = 1; + } else { + searchLength = filterLength; + } + while (searchLength <= filterLength) { + if (this.options.matchInside) { + maxPos = filterLength - searchLength; + } else { + maxPos = 0; + } + pos = 0; + while (pos <= maxPos) { + search = filter.substr(0, searchLength); + if (this.cacheData_[search] !== undefined) { + return this.cacheData_[search]; + } + pos++; + } + searchLength++; + } + } + return false; + }; + + $.dnnAutocompleter.prototype.cacheWrite = function (filter, data) { + if (this.options.useCache) { + if (this.cacheLength_ >= this.options.maxCacheLength) { + this.cacheFlush(); + } + filter = String(filter); + if (this.cacheData_[filter] !== undefined) { + this.cacheLength_++; + } + this.cacheData_[filter] = data; + return this.cacheData_[filter]; + } + return false; + }; + + $.dnnAutocompleter.prototype.cacheFlush = function () { + this.cacheData_ = {}; + this.cacheLength_ = 0; + }; + + $.dnnAutocompleter.prototype.callHook = function (hook, data) { + var f = this.options[hook]; + if (f && $.isFunction(f)) { + return f(data, this); + } + return false; + }; + + $.dnnAutocompleter.prototype.activate = function () { + var self = this; + if (this.keyTimeout_) { + clearTimeout(this.keyTimeout_); + } + this.keyTimeout_ = setTimeout(function () { + self.activateNow(); + }, this.options.delay); + }; + + $.dnnAutocompleter.prototype.activateNow = function () { + var value = this.beforeUseConverter(this.dom.$elem.val()); + if (value !== this.lastProcessedValue_ && value !== this.lastSelectedValue_) { + this.fetchData(value); + } + }; + + $.dnnAutocompleter.prototype.fetchData = function (value) { + var self = this; + var processResults = function (results, filter) { + if (self.options.processData) { + results = self.options.processData(results); + } + self.showResults(self.filterResults(results, filter), filter); + }; + this.lastProcessedValue_ = value; + if (value.length < this.options.minChars) { + processResults([], value); + } else if (this.options.data) { + processResults(this.options.data, value); + } else { + this.fetchRemoteData(value, function (remoteData) { + processResults(remoteData, value); + }); + } + }; + + $.dnnAutocompleter.prototype.fetchRemoteData = function (filter, callback) { + var data = this.cacheRead(filter); + if (data) { + callback(data); + } else { + var self = this; + var ajaxCallback = function (d) { + var parsed = false; + if (d !== false) { + parsed = self.parseRemoteData(d); + self.cacheWrite(filter, parsed); + } + self.dom.$elem.removeClass(self.options.loadingClass); + callback(parsed); + }; + + this.dom.$elem.addClass(this.options.loadingClass); + // DNN service framework attached if needed + var services = self.options.moduleId ? ($.dnnSF ? $.dnnSF(self.options.moduleId) : null) : null; + $.ajax({ + url: this.makeUrl(filter), + beforeSend: services ? services.setModuleHeaders : null, + success: ajaxCallback, + error: function (jqXhr, textStatus, errorThrown) { + if ($.isFunction(self.options.onError)) { + self.options.onError(jqXhr, textStatus, errorThrown); + } else { + ajaxCallback(false); + } + }, + type: 'GET', + dataType: 'json', + contentType: "application/json" + }); + } + }; + + $.dnnAutocompleter.prototype.setExtraParam = function (name, value) { + var index = $.trim(String(name)); + if (index) { + if (!this.options.extraParams) { + this.options.extraParams = {}; + } + if (this.options.extraParams[index] !== value) { + this.options.extraParams[index] = value; + this.cacheFlush(); + } + } + }; + + $.dnnAutocompleter.prototype.makeUrl = function (param) { + var url = this.options.url; + var params = {}; + params[this.options.queryParamName] = param; + return makeUrl(url, params); + }; + + $.dnnAutocompleter.prototype.parseRemoteData = function (remoteData) { + var data = remoteData; + if (typeof data['d'] != 'undefined') { + data = $.parseJSON(data['d']); + } + return data; + }; + + $.dnnAutocompleter.prototype.filterResult = function (result, filter) { + if (!result.value) { + return false; + } + if (this.options.filterResults) { + var pattern = this.matchStringConverter(filter); + var testValue = this.matchStringConverter(result.value); + if (!this.options.matchCase) { + pattern = pattern.toLowerCase(); + testValue = testValue.toLowerCase(); + } + var patternIndex = testValue.indexOf(pattern); + if (this.options.matchInside) { + return patternIndex > -1; + } else { + return patternIndex === 0; + } + } + return true; + }; + + $.dnnAutocompleter.prototype.filterResults = function (results, filter) { + var filtered = []; + var i, result; + + for (i = 0; i < results.length; i++) { + result = sanitizeResult(results[i]); + if (this.filterResult(result, filter)) { + filtered.push(result); + } + } + if (this.options.sortResults) { + filtered = this.sortResults(filtered, filter); + } + if (this.options.maxItemsToShow > 0 && this.options.maxItemsToShow < filtered.length) { + filtered.length = this.options.maxItemsToShow; + } + return filtered; + }; + + $.dnnAutocompleter.prototype.sortResults = function (results, filter) { + var self = this; + var sortFunction = this.options.sortFunction; + if (!$.isFunction(sortFunction)) { + sortFunction = function (a, b) { + return sortValueAlpha(a, b, self.options.matchCase); + }; + } + results.sort(function (a, b) { + return sortFunction(a, b, filter, self.options); + }); + return results; + }; + + $.dnnAutocompleter.prototype.matchStringConverter = function (s, a, b) { + var converter = this.options.matchStringConverter; + if ($.isFunction(converter)) { + s = converter(s, a, b); + } + return s; + }; + + $.dnnAutocompleter.prototype.beforeUseConverter = function (s, a, b) { + s = this.getValue(); + var converter = this.options.beforeUseConverter; + if ($.isFunction(converter)) { + s = converter(s, a, b); + } + return s; + }; + + $.dnnAutocompleter.prototype.enableFinishOnBlur = function () { + this.finishOnBlur_ = true; + }; + + $.dnnAutocompleter.prototype.disableFinishOnBlur = function () { + this.finishOnBlur_ = false; + }; + + $.dnnAutocompleter.prototype.createItemFromResult = function (result, filter) { + var self = this; + var $li = $('
  • ' + this.showResult(result.value, result.data, filter) + '
  • '); + $li.data({ value: result.value, data: result.data }) + .click(function () { + self.selectItem($li); + }) + .mousedown(self.disableFinishOnBlur) + .mouseup(self.enableFinishOnBlur) + ; + return $li; + }; + + $.dnnAutocompleter.prototype.getItems = function () { + return $('>ul>li', this.dom.$results); + }; + + $.dnnAutocompleter.prototype.showResults = function (results, filter) { + var numResults = results.length; + var self = this; + var $ul = $('
      '); + var i, result, $li, autoWidth, first = false, $first = false; + + if (numResults) { + for (i = 0; i < numResults; i++) { + result = results[i]; + $li = this.createItemFromResult(result, filter); + $ul.append($li); + if (first === false) { + first = String(result.value); + $first = $li; + $li.addClass(this.options.firstItemClass); + } + if (i === numResults - 1) { + $li.addClass(this.options.lastItemClass); + } + } + + this.dom.$results.html($ul).show(); + + // Always recalculate position since window size or + // input element location may have changed. + this.position(); + if (this.options.autoWidth) { + autoWidth = this.dom.$elem.outerWidth() - this.dom.$results.outerWidth() + this.dom.$results.width(); + this.dom.$results.css(this.options.autoWidth, autoWidth); + } + this.getItems().hover( + function () { self.focusItem(this); }, + function () { /* void */ } + ); + if (this.autoFill(first, filter) || this.options.selectFirst || (this.options.selectOnly && numResults === 1)) { + this.focusItem($first); + } + this.active_ = true; + + //Select the first one as default + this.focusNext(); + + } else { + this.hideResults(); + this.active_ = false; + } + }; + + $.dnnAutocompleter.prototype.showResult = function (value, data, filter) { + if ($.isFunction(this.options.showResult)) { + return this.options.showResult(value, data); + } else { + // add highlight keywords + var regex = new RegExp('(' + filter + ')', 'gi'); + return value.replace(regex, function ($0, $1) { + return ('' + $1 + ''); + }); + } + }; + + $.dnnAutocompleter.prototype.autoFill = function (value, filter) { + var lcValue, lcFilter, valueLength, filterLength; + if (this.options.autoFill && this.lastKeyPressed_ !== 8) { + lcValue = String(value).toLowerCase(); + lcFilter = String(filter).toLowerCase(); + valueLength = value.length; + filterLength = filter.length; + if (lcValue.substr(0, filterLength) === lcFilter) { + var d = this.getDelimiterOffsets(); + var pad = d.start ? ' ' : ''; // if there is a preceding delimiter + this.setValue(pad + value); + var start = filterLength + d.start + pad.length; + var end = valueLength + d.start + pad.length; + this.selectRange(start, end); + return true; + } + } + return false; + }; + + $.dnnAutocompleter.prototype.focusNext = function () { + this.focusMove(+1); + }; + + $.dnnAutocompleter.prototype.focusPrev = function () { + this.focusMove(-1); + }; + + $.dnnAutocompleter.prototype.focusMove = function (modifier) { + var $items = this.getItems(); + modifier = sanitizeInteger(modifier, 0); + if (modifier) { + for (var i = 0; i < $items.length; i++) { + if ($($items[i]).hasClass(this.selectClass_)) { + this.focusItem(i + modifier); + return; + } + } + } + this.focusItem(0); + }; + + $.dnnAutocompleter.prototype.focusItem = function (item) { + var $item, $items = this.getItems(); + if ($items.length) { + $items.removeClass(this.selectClass_).removeClass(this.options.selectClass); + if (typeof item === 'number') { + if (item < 0) { + item = 0; + } else if (item >= $items.length) { + item = $items.length - 1; + } + $item = $($items[item]); + } else { + $item = $(item); + } + if ($item) { + $item.addClass(this.selectClass_).addClass(this.options.selectClass); + } + } + }; + + $.dnnAutocompleter.prototype.selectCurrent = function () { + var $item = $('li.' + this.selectClass_, this.dom.$results); + if ($item.length === 1) { + this.selectItem($item); + } else { + this.deactivate(false); + } + }; + + $.dnnAutocompleter.prototype.selectItem = function ($li) { + var value = $li.data('value'); + var data = $li.data('data'); + var displayValue = this.displayValue(value, data); + var processedDisplayValue = this.beforeUseConverter(displayValue); + this.lastProcessedValue_ = processedDisplayValue; + this.lastSelectedValue_ = processedDisplayValue; + var d = this.getDelimiterOffsets(); + var delimiter = this.options.delimiterChar; + var elem = this.dom.$elem; + var extraCaretPos = 0; + if (this.options.useDelimiter) { + // if there is a preceding delimiter, add a space after the delimiter + if (elem.val().substring(d.start - 1, d.start) == delimiter && delimiter != ' ') { + displayValue = ' ' + displayValue; + } + // if there is not already a delimiter trailing this value, add it + if (elem.val().substring(d.end, d.end + 1) != delimiter && this.lastKeyPressed_ != this.options.delimiterKeyCode) { + displayValue = displayValue + delimiter; + } else { + // move the cursor after the existing trailing delimiter + extraCaretPos = 1; + } + } + this.setValue(displayValue); + this.setCaret(d.start + displayValue.length + extraCaretPos); + this.callHook('onItemSelect', { value: value, data: data }); + this.deactivate(true); + elem.trigger('result', value); + }; + + $.dnnAutocompleter.prototype.displayValue = function (value, data) { + if ($.isFunction(this.options.displayValue)) { + return this.options.displayValue(value, data); + } + return value; + }; + + $.dnnAutocompleter.prototype.hideResults = function () { + this.dom.$results.hide(); + }; + + $.dnnAutocompleter.prototype.deactivate = function (finish) { + if (this.finishTimeout_) { + clearTimeout(this.finishTimeout_); + } + if (this.keyTimeout_) { + clearTimeout(this.keyTimeout_); + } + if (finish) { + if (this.lastProcessedValue_ !== this.lastSelectedValue_) { + if (this.options.mustMatch) { + this.setValue(''); + } + this.callHook('onNoMatch'); + } + if (this.active_) { + this.callHook('onFinish'); + } + this.lastKeyPressed_ = null; + this.lastProcessedValue_ = null; + this.lastSelectedValue_ = null; + this.active_ = false; + } + this.hideResults(); + }; + + $.dnnAutocompleter.prototype.selectRange = function (start, end) { + var input = this.dom.$elem.get(0); + if (input.setSelectionRange) { + input.focus(); + input.setSelectionRange(start, end); + } else if (input.createTextRange) { + var range = input.createTextRange(); + range.collapse(true); + range.moveEnd('character', end); + range.moveStart('character', start); + range.select(); + } + }; + + $.dnnAutocompleter.prototype.setCaret = function (pos) { + this.selectRange(pos, pos); + }; + + $.dnnAutocompleter.prototype.getCaret = function () { + var elem = this.dom.$elem, s, e, range; + if (!$.support.cssFloat) { + // ie + var selection = document.selection; + if (elem[0].tagName.toLowerCase() != 'textarea') { + var val = elem.val(); + range = selection.createRange().duplicate(); + range.moveEnd('character', val.length); + s = (range.text == '' ? val.length : val.lastIndexOf(range.text)); + range = selection.createRange().duplicate(); + range.moveStart('character', -val.length); + e = range.text.length; + } else { + range = selection.createRange(); + var storedRange = range.duplicate(); + storedRange.moveToElementText(elem[0]); + storedRange.setEndPoint('EndToEnd', range); + s = storedRange.text.length - range.text.length; + e = s + range.text.length; + } + } else { + // ff, chrome, safari + s = elem[0].selectionStart; + e = elem[0].selectionEnd; + } + return { + start: s, + end: e + }; + }; + + $.dnnAutocompleter.prototype.setValue = function (value) { + if (this.options.useDelimiter) { + // set the substring between the current delimiters + var val = this.dom.$elem.val(); + var d = this.getDelimiterOffsets(); + var preVal = val.substring(0, d.start); + var postVal = val.substring(d.end); + value = preVal + value + postVal; + } + this.dom.$elem.val(value).blur(); + }; + + $.dnnAutocompleter.prototype.getValue = function () { + var val = this.dom.$elem.val(); + if (this.options.useDelimiter) { + var d = this.getDelimiterOffsets(); + return val.substring(d.start, d.end).trim(); + } else { + return val; + } + }; + + $.dnnAutocompleter.prototype.getDelimiterOffsets = function () { + var val = this.dom.$elem.val(); + if (this.options.useDelimiter) { + var preCaretVal = val.substring(0, this.getCaret().start); + var start = preCaretVal.lastIndexOf(this.options.delimiterChar) + 1; + var postCaretVal = val.substring(this.getCaret().start); + var end = postCaretVal.indexOf(this.options.delimiterChar); + if (end == -1) end = val.length; + end += this.getCaret().start; + } else { + start = 0; + end = val.length; + } + return { + start: start, + end: end + }; + }; +})(jQuery); + +(function ($) { + // dnn customized tags + var delimiter = new Array(); + var tagsCallbacks = new Array(); + $.fn.dnnDoAutosize = function (o) { + var minWidth = $(this).data('minwidth'), + maxWidth = $(this).data('maxwidth'), + val = '', + input = $(this), + testSubject = $('#' + $(this).data('tester_id')); + + if (val === (val = input.val())) { return; } + + // Enter new content into testSubject + var escaped = val.replace(/&/g, '&').replace(/\s/g, ' ').replace(//g, '>'); + testSubject.html(escaped); + // Calculate new width + whether to change + var testerWidth = testSubject.width(), + newWidth = (testerWidth + o.comfortZone) >= minWidth ? testerWidth + o.comfortZone : minWidth, + currentWidth = input.width(), + isValidWidthChange = (newWidth < currentWidth && newWidth >= minWidth) + || (newWidth > minWidth && newWidth < maxWidth); + + // Animate width + if (isValidWidthChange) { + input.width(newWidth); + } + }; + + $.fn.dnnResetAutosize = function (options) { + var minWidth = $(this).data('minwidth') || options.minInputWidth || $(this).width(), + maxWidth = $(this).data('maxwidth') || options.maxInputWidth || ($(this).closest('.dnnTagsInput').width() - options.inputPadding), + $input = $(this); + + var left = 0; + var $lastSpan = $(this).closest('.dnnTagsInput').find('> span').last(); + if ($lastSpan.length > 0) { + left = $lastSpan.offset().left - $lastSpan.parent().offset().left + $lastSpan.outerWidth(); + } + var availableWidth = maxWidth - left; + if (availableWidth < parseInt(minWidth)) { + availableWidth = maxWidth; + } + + $input.css('width', availableWidth); + }; + + $.fn.dnnAddTag = function (value, options) { + options = jQuery.extend({ focus: false, callback: true }, options); + this.each(function () { + var id = $(this).attr('id'); + var tagslist = $(this).val().split(delimiter[id]); + if (tagslist[0] == '') { + tagslist = new Array(); + } + value = value.replace(/<.*?>/g, ''); + value = jQuery.trim(value); + var skipTag; + if (options.unique) { + skipTag = $(this).dnnTagExist(value); + if (skipTag == true) { + //Marks fake input as not_valid to let styling it + $('#' + id + '_tag').addClass('dnnTagsInvalid'); + } + else + $('#' + id + '_tag').removeClass('dnnTagsInvalid'); + } else { + skipTag = false; + $('#' + id + '_tag').removeClass('dnnTagsInvalid'); + } + + if (value != '' && skipTag != true) { + $('').addClass('tag').append( + $('').text(value).append('  '), + $('', { + href: '#', + title: 'Removing tag' + }).click(function () { + return $('#' + id).dnnRemoveTag(escape(value)); + }) + ).insertBefore('#' + id + '_addTag'); + + tagslist.push(value); + + $('#' + id + '_tag').val(''); + if (options.focus) { + $('#' + id + '_tag').focus(); + } else { + $('#' + id + '_tag').blur(); + } + + $.fn.dnnTagsInput.updateTagsField(this, tagslist); + var f; + if (options.callback && tagsCallbacks[id] && tagsCallbacks[id]['onAddTag']) { + f = tagsCallbacks[id]['onAddTag']; + f.call(this, value); + } + if (tagsCallbacks[id] && tagsCallbacks[id]['onChange']) { + var i = tagslist.length; + f = tagsCallbacks[id]['onChange']; + f.call(this, $(this), tagslist[i - 1]); + } + } + }); + return false; + }; + + $.fn.dnnRemoveTag = function (value) { + value = unescape(value); + this.each(function () { + var id = $(this).attr('id'); + var old = $(this).val().split(delimiter[id]); + $('#' + id + '_tagsinput .tag').remove(); + var str = ''; + for (var i = 0; i < old.length; i++) { + if (old[i] != value) { + str = str + delimiter[id] + old[i]; + } + } + $.fn.dnnTagsInput.importTags(this, str); + if (tagsCallbacks[id] && tagsCallbacks[id]['onRemoveTag']) { + var f = tagsCallbacks[id]['onRemoveTag']; + f.call(this, value); + } + }); + + return false; + }; + + $.fn.dnnTagExist = function (val) { + var id = $(this).attr('id'), + tagslist = $(this).val().split(delimiter[id]); + return (jQuery.inArray(val, tagslist) >= 0); + }; + + $.fn.dnnImportTags = function (str) { + var id = $(this).attr('id'); + $('#' + id + '_tagsinput .tag').remove(); + $.fn.dnnTagsInput.importTags(this, str); + }; + + $.fn.dnnTagsInput = function (options) { + var onError = null; + var triggerOnError = function (handler) { + if (!onError) { + onError = setTimeout(function () { + onError = null; + if (handler) handler(); + }, 0); + } + }; + var settings = jQuery.extend({ + interactive: true, + defaultText: 'Add a tag', + minChars: 0, + maxChars: 50, + maxTags: 16, + lessThanMinCharsErrorText: 'A tag cannot be less than {0} characters long', + lessThanMinCharsErrorTitle: 'Tag Length Not Reached', + moreThanMaxCharsErrorText: 'A tag cannot be more than {0} characters long', + moreThanMaxCharsErrorTitle: 'Tag Length Exceeded', + moreThanMaxTagsErrorText: 'A maximum of {0} tags can be attached here', + moreThanMaxTagsErrorTitle: 'Tags limit exceeded', + onErrorLessThanMinChars: function () { // can be customised by module dev + $.dnnAlert({ text: String.format(settings.lessThanMinCharsErrorText, settings.minChars), title: settings.lessThanMinCharsErrorTitle }); + }, + onErrorMoreThanMaxChars: function () { // can be customised by module dev + $.dnnAlert({ text: String.format(settings.moreThanMaxCharsErrorText, settings.maxChars), title: settings.moreThanMaxCharsErrorTitle }); + }, + onErrorMoreThanMaxTags: function () { // can be customised by module dev + $.dnnAlert({ text: String.format(settings.moreThanMaxTagsErrorText, settings.maxTags), title: settings.moreThanMaxTagsErrorTitle }); + }, + + width: '45%', + autocomplete: { selectFirst: false }, + 'hide': true, + 'delimiter': ',', + 'unique': true, + removeWithBackspace: true, + placeholderColor: '#999', + normalColor: '#666', + autosize: true, + comfortZone: 20, + inputPadding: 6 * 2 + + }, options); + + this.each(function () { + var instance = $(this).data('dnnTagInput'); + if (instance) return this; + if (settings.hide) { + $(this).hide(); + } + var id = $(this).attr('id'); + if (!id || delimiter[$(this).attr('id')]) { + id = $(this).attr('id', 'tags' + new Date().getTime()).attr('id'); + } + var data = jQuery.extend({ + pid: id, + real_input: '#' + id, + holder: '#' + id + '_tagsinput', + input_wrapper: '#' + id + '_addTag', + fake_input: '#' + id + '_tag' + }, settings); + + $(this).data('dnnTagInput', data); + + delimiter[id] = data.delimiter; + + if (settings.onAddTag || settings.onRemoveTag || settings.onChange) { + tagsCallbacks[id] = new Array(); + tagsCallbacks[id]['onAddTag'] = settings.onAddTag; + tagsCallbacks[id]['onRemoveTag'] = settings.onRemoveTag; + tagsCallbacks[id]['onChange'] = settings.onChange; + } + + var markup = '
      '; + markup += '
      '; + + if (settings.interactive) { + markup += ''; + } + + markup += '
      '; + markup = markup + '
      '; + + $(markup).insertAfter(this); + + $(data.holder).css({ + 'width': settings.width, + 'min-height': settings.height + }); + + $(data.fake_input).attr("maxlength", settings.maxChars); + + if ($(data.real_input).val() != '') { + $.fn.dnnTagsInput.importTags($(data.real_input), $(data.real_input).val()); + } + if (settings.interactive) { + // placeholder stuff + $(data.fake_input).dnnPlaceholder({ + color: [settings.normalColor, settings.placeholderColor] + }); + + $(data.fake_input).dnnResetAutosize(settings); + $(data.holder).on('click', data, function (event) { + $(event.data.real_input).triggerHandler('focus'); + $(event.data.fake_input).triggerHandler('focus'); + return false; + }); + if (settings.autocomplete_url != undefined) { + if ($.dnnAutocompleter !== undefined) { + if (settings.advanced && settings.advanced.length) { + settings.autocomplete.advanced = settings.advanced; + } + + $(data.fake_input).dnnAutocomplete(settings.autocomplete_url, settings.autocomplete); + $(data.fake_input).on('result', data, function (event, tag) { + if (tag) { + var tagslist = $(event.data.real_input).val().split(delimiter[id]); + if (tagslist[0] == '') { + tagslist = new Array(); + } + if (event.data.maxTags <= tagslist.length) { + if (event.data.onErrorMoreThanMaxTags) + triggerOnError(event.data.onErrorMoreThanMaxTags); + $(data.fake_input).val(''); + } + else + $(event.data.real_input).dnnAddTag(tag, { focus: true, unique: (settings.unique) }); + } + }); + } + } else { + // if a user tabs out of the field, create a new tag + // this is only available if autocomplete is not used. + $(data.fake_input).on('blur', data, function (event) { + var d = $(this).attr('data-default'); + var tagslist = $(event.data.real_input).val().split(delimiter[id]); + if (tagslist[0] == '') { + tagslist = new Array(); + } + if ($(event.data.fake_input).val() != '' && $(event.data.fake_input).val() != d) { + if (event.data.minChars > $(event.data.fake_input).val().length) { + if (event.data.onErrorLessThanMinChars) + triggerOnError(event.data.onErrorLessThanMinChars); + $(data.fake_input).val(''); + } + else if (event.data.maxChars < $(event.data.fake_input).val().length) { + if (event.data.onErrorMoreThanMaxChars) + triggerOnError(event.data.onErrorMoreThanMaxChars); + $(data.fake_input).val(''); + } + else if (event.data.maxTags <= tagslist.length) { + if (event.data.onErrorMoreThanMaxTags) + triggerOnError(event.data.onErrorMoreThanMaxTags); + $(data.fake_input).val(''); + } + else{ + var tags = $(event.data.fake_input).val().split(delimiter[id]); + for(var i = 0; i < tags.length; i++){ + $(event.data.real_input).dnnAddTag(tags[i], { focus: true, unique: (settings.unique) }); + } + } + $(event.data.fake_input).dnnResetAutosize(settings); + } + + return false; + }); + + } + + function tagItems(data, event) { + var tagslist = $(event.data.real_input).val().split(delimiter[id]); + if (tagslist[0] == '') { + tagslist = new Array(); + } + if (event.data.minChars > $(event.data.fake_input).val().length) { + if (event.data.onErrorLessThanMinChars) + triggerOnError(event.data.onErrorLessThanMinChars); + $(data.fake_input).val(''); + } + else if (event.data.maxChars < $(event.data.fake_input).val().length) { + if (event.data.onErrorMoreThanMaxChars) + triggerOnError(event.data.onErrorMoreThanMaxChars); + $(data.fake_input).val(''); + } + else if (event.data.maxTags <= tagslist.length) { + if (event.data.onErrorMoreThanMaxTags) + triggerOnError(event.data.onErrorMoreThanMaxTags); + $(data.fake_input).val(''); + } + else { + var tags = $(event.data.fake_input).val().split(delimiter[id]); + for (var i = 0; i < tags.length; i++) { + $(event.data.real_input).dnnAddTag(tags[i], { focus: true, unique: (settings.unique) }); + } + } + + $(event.data.fake_input).dnnResetAutosize(settings); + return false; + } + + var clickedOnAutoComplete = false; + + $(document).mousedown(function (e) { + if ($(e.target).hasClass("dnn_acSelect") || $(e.target).parent().hasClass('dnn_acSelect')) { + clickedOnAutoComplete = true; + } + }); + + var tagTooLongErrMsg = $('' + String.format(settings.moreThanMaxCharsErrorText, settings.maxChars) + ''); + // if user types a comma, create a new tag + $(data.fake_input).on('keypress keydown blur', data, function (event) { + if ($(this).val() === "" || clickedOnAutoComplete) { + return; + } + var currValLength = $(this).val().length; + if ((currValLength >= settings.maxChars) && !(event.which == event.data.delimiter.charCodeAt(0) || event.which == 13 || event.which == 9)) { + tagTooLongErrMsg.insertAfter($(this)).show().delay(1500).fadeOut(1000); + } + if (event.which == event.data.delimiter.charCodeAt(0) || event.which == 13 || event.which == 9 || event.type == "blur") { + event.preventDefault(); + if (!clickedOnAutoComplete) { + tagItems(data, event); + } + clickedOnAutoComplete = false; + } else if (event.data.autosize) { + $(event.data.fake_input).dnnDoAutosize(settings); + } + return true; + }); + //Delete last tag on backspace + data.removeWithBackspace && $(data.fake_input).on('keydown', function (event) { + if (event.keyCode == 8 && $(this).val() == '') { + event.preventDefault(); + var lastTag = $(this).closest('.dnnTagsInput').find('.tag:last').text(); + var lastTagId = $(this).attr('id').replace(/_tag$/, ''); + lastTag = lastTag.replace(/[\s]+$/, ''); + $('#' + lastTagId).dnnRemoveTag(escape(lastTag)); + $(this).trigger('focus'); + } + }); + $(data.fake_input).blur(); + + //Removes the not_valid class when user changes the value of the fake input + if (data.unique) { + $(data.fake_input).keydown(function (event) { + if (event.keyCode == 8 || String.fromCharCode(event.which).match(/\w+|[áéíóúÁÉÍÓÚñÑ,/]+/)) { + $(this).removeClass('dnnTagsInvalid'); + } + }); + } + + } // if settings.interactive + return this; + }); + return this; + }; + + $.fn.dnnTagsInput.updateTagsField = function (obj, tagslist) { + var id = $(obj).attr('id'); + $(obj).val(tagslist.join(delimiter[id])); + }; + + $.fn.dnnTagsInput.importTags = function (obj, val) { + $(obj).val(''); + var id = $(obj).attr('id'); + var tags = val.split(delimiter[id]); + for (var i = 0; i < tags.length; i++) { + $(obj).dnnAddTag(tags[i], { focus: false, callback: false }); + } + if (tagsCallbacks[id] && tagsCallbacks[id]['onChange']) { + var f = tagsCallbacks[id]['onChange']; + f.call(obj, obj, tags[i]); + } + }; + + $.fn.dnnPlaceholder = function (options) { + options = $.extend({}, { + cssClass: 'dnnPlaceholder', + color: [] + }, options); + + this.each(function () { + var $this = $(this); + var instance = $this.data('dnnPlaceHolder'); + if (instance) return true; + $this.data('dnnPlaceHolder', true); + + var placeholderSupported = ('placeholder' in $this[0]); + if (placeholderSupported) + $this.attr('placeholder', $this.attr('data-default')); + else { + var $fakeInput = $('') + .attr('class', $this.attr('class')) + .attr('style', $this.attr('style')) + .val($this.attr('data-default')); + + $this.hide().after($fakeInput); + if (options.color.length === 2) { + $fakeInput.css('color', options.color[1]); + $this.css('color', options.color[0]); + } else { + $fakeInput.addClass(options.cssClass); + } + + + $fakeInput.on('focus', function(event) { + $fakeInput.hide(); + $this.show().focus(); + }); + + $this.on('blur', function (event) { + var d = $this.attr('data-default'); + if ($this.val() === '') { + $this.hide(); + $fakeInput.show(); + } + }); + + var events = $._data(this, 'events')['blur']; + var first = events.pop(); + events.splice(0, 0, first); + } + + return true; + }); + + return this; + }; +})(jQuery); + +(function ($) { + // dnnForm customised client side validation + $.fn.toggleErrorMessage = function (options) { + var defaultOptions = { + errorMessage: "Error message", + errorCls: "dnnFormError", + show: true, + removeErrorMessage: true + }; + + options = $.extend(defaultOptions, options); + + return this.each(function () { + var dnnFormItem = $(this).closest('.dnnFormItem'); + if (options.show) { + var errorSpan = dnnFormItem.find('span.dnnFormMessage.' + options.errorCls); + if (errorSpan.length) { + errorSpan.html(options.errorMessage); + } else { + errorSpan = $('' + options.errorMessage + ''); + dnnFormItem.append(errorSpan); + } + + if (this.tagName.toLowerCase() == 'div') { + // customised controls + if ($(this).hasClass('RadComboBox')) { + // RadComboBox + $(this).addClass('dnnError'); + } + } + else { + if ($(this).parent().hasClass('RadPicker')) { + // RadDate Picker + $(this).parent().find('input.riTextBox').css('border', '1px solid red'); + } + else if ($(this).hasClass('dnnSpinnerInput')) { + // Spinner + $(this).parent().css('border', '1px solid red'); + } + else { + // normal ctrl + $(this).css('border', '1px solid red'); + } + } + } + else { + if (options.removeErrorMessage) + dnnFormItem.find('span.' + options.errorCls).remove(); + else + dnnFormItem.find('span.' + options.errorCls).hide(); + + if (this.tagName.toLowerCase() == 'div') { + // customised controls + if ($(this).hasClass('RadComboBox')) { + // RadComboBox + $(this).removeClass('dnnError'); + + } + } + else { + if ($(this).hasClass('dnnSpinnerInput')) { + // Spinner + $(this).parent().css('border', '1px solid #ccc'); + } + else { + // normal ctrl + $(this).css('border', '1px solid #ccc'); + } + } + } + }); + }; + $.fn.dnnFormSubmit = function (options) { + var defaultOptions = { + validates: [] + }; + + options = $.extend(defaultOptions, options); + + return this.each(function () { + $(this).click(function () { + var formValidate = true; + for (var i = 0; i < options.validates.length; i++) { + var ele = $('#' + options.validates[i].ele); + var func = options.validates[i].func; + if (ele.length) { + var eleVal = ele.val(); + var eleError = func.call(ele.get(0), eleVal); + if (eleError) { + ele.toggleErrorMessage({ errorMessage: eleError, show: true }); + formValidate = false; + } + else { + ele.toggleErrorMessage({ show: false }); + } + + //ele focus then remove error info + var hideErrorInfo = function () { + $(this).toggleErrorMessage({ show: false }); + }; + + ele.off('focus', hideErrorInfo).on('focus', hideErrorInfo); + } + } + + return formValidate; + }); + }); + }; + + // fix telerik custom datepicker popup arrow position + $.dnnRadPickerHack = function () { + //when click this icon, hide error info + var hideErrorInfo = function () { + $(this).toggleErrorMessage({ show: false, removeErrorMessage: false }); + }; + var dnnRadPickerPopupFix = function () { + if ($.support.cssFloat) { + var id = $(this).attr('id'); + var popupId = id.replace('popupButton', 'calendar_wrapper'); + var popupElement = $('#' + popupId); + var wrapperId = id.replace('popupButton', 'wrapper'); + var wrapperElement = $('#' + wrapperId); + + var popupElementTop = popupElement.parent().position().top; + var wrapperElementTop = wrapperElement.offset().top; + var popupTbl = popupElement.find('.RadCalendar_Default'); + var nextEle = popupTbl.next(); + if (nextEle.hasClass('RadCalendar_Default_PopupArrow_Down') || nextEle.hasClass('RadCalendar_Default_PopupArrow_Up')) + nextEle.remove(); + + if (popupElementTop < wrapperElementTop) { // popup above the calendar ctrl, so show arrow down + popupTbl.after('
      '); + } + else { // popup below the calendar ctrl, so show arrow up + popupTbl.after('
      '); + } + } + + $(this).toggleErrorMessage({ show: false, removeErrorMessage: false }); + }; + $('.RadPicker_Default a.rcCalPopup').off('click', dnnRadPickerPopupFix).on('click', dnnRadPickerPopupFix); + $('.RadPicker_Default .riTextBox').off('focus', hideErrorInfo).on('focus', hideErrorInfo); + }; + + // remove combobox inline style + $.dnnComboBoxLoaded = function (sender) { + if (sender.constructor.__typeName == "Telerik.Web.UI.RadComboBox") { + $(sender._inputDomElement).closest(".RadComboBox").removeAttr("style"); + } + }; + + //fix combobox hide error info + $.dnnComboBoxHack = function (sender) { + $(('#' + sender._clientStateFieldID).replace('_ClientState', '')).toggleErrorMessage({ show: false, removeErrorMessage: false }); + }; + + //fix combobox scroll + $.dnnComboBoxScroll = function (sender) { + if ($.support.cssFloat) { + var container = $(('#' + sender._clientStateFieldID + ' .rcbScroll').replace('ClientState', 'DropDown')); + if (container.data('scrollPane')) { + container.data('scrollPane').data('jsp').reinitialise(); + } else { + container.data('scrollPane', container.jScrollPane()); + } + } + }; + + $.dnnComboBoxItemRequested = function (sender) { + setTimeout(function() { + var container = $(('#' + sender._clientStateFieldID + ' .rcbScroll').replace('ClientState', 'DropDown')); + if (container.data('scrollPane')) { + container.data('scrollPane').data('jsp').reinitialise(); + } + }, 0); + }; + + // fix grid issues + $.dnnGridCreated = function (sender) { + var clientId = sender.ClientID; + var $grid = $('#' + clientId); + $('input.rgSortDesc, input.rgSortAsc', $grid).click(function () { + var href = $(this).parent().find('a').get(0).href; + window.location = href; + return false; + }); + + if ($grid.hasClass('dnnTooltipGrid')) { + $grid.dnnHelperTipDestroy(); + $('.rgRow, .rgAltRow', $grid).each(function () { + var info = "Here is some text will show up and explian more about this information"; + $(this).dnnHelperTip({ helpContent: info, holderId: clientId }); + }); + } + + var grid = $find(clientId); + + // while using customised checkbox - remove onclick event then attach onchange + var headerCheck = $('.rgCheck', $grid); + if (headerCheck.length) { + headerCheck.each(function () { + var checkbox = $(this).find('input[type="checkbox"]').get(0); + var onclick = checkbox.onclick; + checkbox.onchange = onclick; + checkbox.onclick = null; + }); + + // when use customised scrollbar and customised checkbox, the row cannot be correctly selected + $('.rgDataDiv input[type="checkbox"]', $grid).change(function () { + var masterTable = grid.get_masterTableView(); + var rowIndex = $(this).closest('tr').get(0).rowIndex; + var checked = this.checked; + if (checked) + masterTable.selectItem(rowIndex); + else + masterTable.deselectItem(rowIndex); + }); + } + + // initialize dnnGrid customised scrollbar + $('.rgDataDiv').each(function () { + var $this = $(this); + var ele = $this.get(0); + ele.scrollPane = $this.jScrollPane(); + var api = ele.scrollPane.data('jsp'); + var throttleTimeout; + $(window).on( + 'resize', + function () { + if (!$.support.cssFloat) { + if (throttleTimeout) { + clearTimeout(throttleTimeout); + throttleTimeout = null; + } + throttleTimeout = setTimeout( + function () { + api.reinitialise(); + throttleTimeout = null; + }, + 50 + ); + } else { + api.reinitialise(); + } + } + ); + if (window.__rgDataDivScrollTopPersistArray && window.__rgDataDivScrollTopPersistArray.length) { + var y = window.__rgDataDivScrollTopPersistArray.pop(); + api.scrollToY(y); + } + }); + }; +})(jQuery); + +(function ($) { + var types = ['DOMMouseScroll', 'mousewheel']; + if ($.event.fixHooks) { + for (var i = types.length; i;) { + $.event.fixHooks[types[--i]] = $.event.mouseHooks; + } + } + $.event.special.mousewheel = { + setup: function () { + if (this.addEventListener) { + for (var i = types.length; i;) { + this.addEventListener(types[--i], handler, false); + } + } else { + this.onmousewheel = handler; + } + }, + + teardown: function () { + if (this.removeEventListener) { + for (var i = types.length; i;) { + this.removeEventListener(types[--i], handler, false); + } + } else { + this.onmousewheel = null; + } + } + }; + + $.fn.extend({ + mousewheel: function (fn) { + return fn ? this.on("mousewheel", fn) : this.trigger("mousewheel"); + }, + + unmousewheel: function (fn) { + return this.off("mousewheel", fn); + } + }); + + function handler(event) { + var orgEvent = event || window.event, + args = [].slice.call(arguments, 1), + delta = 0, + deltaX = 0, + deltaY = 0; + event = $.event.fix(orgEvent); + event.type = "mousewheel"; + + // Old school scrollwheel delta + if (orgEvent.wheelDelta) { delta = orgEvent.wheelDelta / 120; } + if (orgEvent.detail) { delta = -orgEvent.detail / 3; } + + // New school multidimensional scroll (touchpads) deltas + deltaY = delta; + + // Gecko + if (orgEvent.axis !== undefined && orgEvent.axis === orgEvent.HORIZONTAL_AXIS) { + deltaY = 0; + deltaX = -1 * delta; + } + + // Webkit + if (orgEvent.wheelDeltaY !== undefined) { deltaY = orgEvent.wheelDeltaY / 120; } + if (orgEvent.wheelDeltaX !== undefined) { deltaX = -1 * orgEvent.wheelDeltaX / 120; } + + // Add event and delta to the front of the arguments + args.unshift(event, delta, deltaX, deltaY); + return ($.event.dispatch || $.event.handle).apply(this, args); + } + +})(jQuery); + +(function ($) { + $.fn.dnnFileInput = function (options) { + var opts = $.extend({}, $.fn.dnnFileInput.defaultOptions, options); + + return this.each(function () { + var $ctrl = $(this); + if ($ctrl.hasClass('normalFileUpload')) return; + + if (this.wrapper) + return; + + //ignore decoration for elements in rad control. + if ($ctrl.parents().hasClass("RadUpload")) + return; + + // if this.wrapper is undefined, then we check if parent node is a wrapper + if (this.parentNode && this.parentNode.tagName.toLowerCase() == 'span' && $ctrl.parent().hasClass('dnnInputFileWrapper')) { + return; + } + + this.wrapper = $(""); + var text = $ctrl.data('text'); + text = text || 'Choose File'; + this.wrapper.text(text); + $ctrl.wrap(this.wrapper); + $ctrl.data("wrapper", $ctrl.parent()); + + if (opts.showSelectedFileNameAsButtonText) { + $ctrl.change(function () { + var val = $(this).val(); + if (val != '') { + var lastIdx = val.lastIndexOf('\\') + 1; + val = val.substring(lastIdx, val.length); + } else { + val = text; + } + $(this).data("wrapper").get(0).childNodes[0].nodeValue = val; + }); + } + }); + }; + + $.fn.dnnFileInput.defaultOptions = { + buttonClass: 'dnnSecondaryAction', + showSelectedFileNameAsButtonText: true + }; +})(jQuery); + +(function ($) { + var supportAjaxUpload = function () { + var xhr = new XMLHttpRequest; + return !!(xhr && ('upload' in xhr) && ('onprogress' in xhr.upload)); + }; + + $.fn.dnnFileUpload = function (settings) { + return this.each(function () { + // set scope and settings, service + var scope = $(this).attr('id'); + window.dnn.dnnFileUpload.setSettings(scope, settings); + var service = $.dnnSF(); + + // hide progress + $('#' + settings.progressBarId).parent().hide(); + // detect draggable support or not + var droppableSpan = $('#' + settings.dropZoneId + '>span'); + if ('draggable' in document.createElement('span')) { + droppableSpan.show(); + } + else { + droppableSpan.hide(); + } + + // set file upload + var url = service.getServiceRoot('internalservices') + 'fileupload/postfile'; + if (!supportAjaxUpload()) { + var antiForgeryToken = $('input[name="__RequestVerificationToken"]').val(); + url += '?__RequestVerificationToken=' + antiForgeryToken; + } + + $('#' + scope + ' input[type="file"]').fileupload({ + url: url, + beforeSend: service.setModuleHeaders, + dropZone: $('#' + settings.dropZoneId), + pasteZone: null, + replaceFileInput: false, + submit: function (e, data) { + data.formData = { folder: settings.folder, filter: settings.fileFilter, overwrite: 'true' }; + return true; + }, + progressall: function (e, data) { + var progress = parseInt(data.loaded / data.total * 100, 10); + if (progress < 100) { + $('#' + settings.progressBarId).parent().show(); + $('#' + settings.progressBarId + '>div').css('width', progress + '%'); + } + else + $('#' + settings.progressBarId).parent().hide(); + }, + done: function (e, data) { + $('#' + settings.progressBarId).parent().hide(); + var img = new Image(); + $(img).on('load', function () { + $('#' + settings.dropZoneId + ' img').remove(); + $(img).css({ 'max-width': 180, 'max-height': 150 }).insertBefore($('#' + settings.dropZoneId + ' span')); + }); + var src; + if (data.dataType && typeof(data.result) == "object" && data.result.length) { + data.result = JSON.parse(data.result.text()); + } else { + data.result = JSON.parse(data.result); + } + var testContent = $('
      ' + data.result.FilePath + '
      '); + if (testContent.length) { + src = testContent.text(); + } + else + src = data.result; + + if (src && $.trim(src)) { + var profileImagePath = dnn.getVar("sf_siteRoot", "/") + 'DnnImageHandler.ashx?mode=securefile&fileId=' + data.result.FileId + '&MaxWidth=180&MaxHeight=150'; + img.src = profileImagePath; + + var fileName = data.result.FilePath.replace('\\', '/'); + if (fileName.indexOf('/') > -1) { + fileName = fileName.split('/')[fileName.split('/').length - 1]; + } + if (fileName.indexOf('?') > -1) { + fileName = fileName.split('?')[0]; + } + + dnn[settings.filesComboId].refresh(dnn[settings.foldersComboId].selectedItem().key); + dnn[settings.filesComboId].selectedItem({ key: data.result.FileId, value: fileName}); + } + }, + fail: function (e, data) { + $('#' + settings.progressBarId).parent().hide(); + var resp = JSON.parse(data.jqXHR.responseText); + alert(resp.Message); + } + }); + + $('#' + scope + ' input[name=uploadFileButton]').click(function() { + var instance = dnn[settings.fileUploadId]; + + var options = instance.options; + if (dnn[settings.foldersComboId].selectedItem() != null) { + instance.options.folderPicker.initialState.selectedItem = dnn[settings.foldersComboId].selectedItem(); + instance.options.folderPath = window.dnn.dnnFileUpload.getSelectedPath(dnn[settings.foldersComboId]); + } + + instance.show(options); + + window.dnn.dnnFileUpload.updateExpandPath(dnn[settings.foldersComboId], instance._panel._folderPicker.id()); + + instance._panel.$element.on("onfileuploadcomplete", function (event, data) { + if (typeof data == "string") { + // for modern browsers + data = JSON.parse(data); + }else{ + // for IE8-9 + var b = data[0]; + data = JSON.parse(b.body.innerText); + } + if (data && data.fileId) { + var folderPicker = instance._panel._folderPicker; + dnn[settings.foldersComboId].selectedItem(folderPicker.selectedItem()); + window.dnn.dnnFileUpload.Folders_Changed(dnn[settings.foldersComboId].selectedItem(), dnn[settings.foldersComboId].$element); + window.dnn.dnnFileUpload.updateExpandPath(folderPicker, settings.foldersComboId); + + dnn[settings.filesComboId].refresh(dnn[settings.foldersComboId].selectedItem().key); + dnn[settings.filesComboId].selectedItem({ key: data.fileId.toString(), value: data.fileName }); + window.dnn.dnnFileUpload.Files_Changed(dnn[settings.filesComboId].selectedItem(), dnn[settings.filesComboId].$element); + } + }); + }); + + // set initial thumb image + setTimeout(function () { + dnn[settings.filesComboId].options.services.parameters.parentId = settings.selectedFolderId; + var filesCombo = dnn[settings.filesComboId]; + var selectedFileId = filesCombo.selectedItem() ? filesCombo.selectedItem().key : null; + var fileId = selectedFileId ? parseInt(selectedFileId) : 0; + if (fileId > 0) { + var maxWidth = 180, maxHeight = 150; + var profileImagePath = dnn.getVar("sf_siteRoot", "/") + 'DnnImageHandler.ashx?mode=securefile&fileId=' + fileId + '&MaxWidth=' + maxWidth + '&MaxHeight=' + maxHeight; + var img = new Image(); + + $(img).on('load', function () { + $('#' + settings.dropZoneId + ' img').remove(); + $(img).css({ 'max-width': maxWidth, 'max-height': maxHeight }).insertBefore($('#' + settings.dropZoneId + ' span')); + }); + img.src = profileImagePath; + } + }, 500); + }); + }; + + if (typeof window.dnn === 'undefined') window.dnn = {}; + window.dnn.dnnFileUpload = window.dnn.dnnFileUpload || {}; + window.dnn.dnnFileUpload.settings = {}; + window.dnn.dnnFileUpload.setSettings = function (scope, settings) { + window.dnn.dnnFileUpload.settings[scope] = settings; + }; + window.dnn.dnnFileUpload.getSettings = function (sender) { + var scope = sender.closest('.dnnFileUploadScope').attr('id'); + return window.dnn.dnnFileUpload.settings[scope]; + }; + window.dnn.dnnFileUpload.Folders_Changed = function (node, sender) { + var settings = window.dnn.dnnFileUpload.getSettings(sender); + if (!settings) return false; + + if (node) { + //get the selected folder path + var selectedPathArray = dnn[settings.foldersComboId].selectedPath(); + if (selectedPathArray.length === 0 && settings.folder) { + return settings.folder; + } + var selectedPath = ""; + if (selectedPathArray.length > 1) { + for (var i = 1, size = selectedPathArray.length; i < size; i++) { + selectedPath += selectedPathArray[i].name + "/"; + } + } + settings.folder = selectedPath; + + dnn[settings.filesComboId].refresh(node.key); + dnn[settings.filesComboId].selectedItem(null); + window.dnn.dnnFileUpload.Files_Changed({ key: null }, $('#' + settings.filesComboId)); + } + }; + window.dnn.dnnFileUpload.Files_Changed = function (node, sender) { + var settings = window.dnn.dnnFileUpload.getSettings(sender); + if (!settings) return; + + if (node) { + var fileId = node.key; + if (fileId) { + var maxWidth = 180, maxHeight = 150; + var profileImagePath = dnn.getVar("sf_siteRoot", "/") + 'DnnImageHandler.ashx?mode=securefile&fileId=' + fileId + '&MaxWidth=' + maxWidth + '&MaxHeight=' + maxHeight; + var img = new Image(); + + $(img).on('load', function () { + $('#' + settings.dropZoneId + ' img').remove(); + $(img).css({ 'max-width': maxWidth, 'max-height': maxHeight }).insertBefore($('#' + settings.dropZoneId + ' span')); + }); + img.src = profileImagePath; + } + else + $('#' + settings.dropZoneId + ' img').remove(); + } + }; + window.dnn.dnnFileUpload.updateExpandPath = function(dropDownList, targetId) { + //set expand path + var selectedPaths = dropDownList.selectedPath(); + var expandPath = ""; + if (selectedPaths.length == 0) { //which means the tree view hasn't opened. + expandPath = dnn.getVar(dropDownList.id() + '_expandPath'); + } + else if (selectedPaths.length > 1) { + for (var i = 0; i < selectedPaths.length - 1; i++) { + if (expandPath == "") { + expandPath = selectedPaths[i].id; + } else { + expandPath = expandPath + "," + selectedPaths[i].id; + } + } + } + + if (expandPath != "") { + dnn.setVar(targetId + '_expandPath', expandPath); + } + }; + window.dnn.dnnFileUpload.getSelectedPath = function(dropDownList) { + var selectedPathArray = dropDownList.selectedPath(); + var settings = window.dnn.dnnFileUpload.getSettings(dropDownList.$element); + if (selectedPathArray.length === 0 && settings.folder) { + return settings.folder; + } + var selectedPath = ""; + if (selectedPathArray.length > 1) { + for (var i = 1, size = selectedPathArray.length; i < size; i++) { + selectedPath += selectedPathArray[i].name + "/"; + } + } + return selectedPath; + }; +})(jQuery); + +(function ($) { + /* BELOW jscrollPane code */ + $.fn.jScrollPane = function (settings) { + // JScrollPane "class" - public methods are available through $('selector').data('jsp') + function JScrollPane(elem, s) { + var settings, jsp = this, pane, paneWidth, paneHeight, container, contentWidth, contentHeight, + percentInViewH, percentInViewV, isScrollableV, isScrollableH, verticalDrag, dragMaxY, + verticalDragPosition, horizontalDrag, dragMaxX, horizontalDragPosition, + verticalBar, verticalTrack, scrollbarWidth, verticalTrackHeight, verticalDragHeight, arrowUp, arrowDown, + horizontalBar, horizontalTrack, horizontalTrackWidth, horizontalDragWidth, arrowLeft, arrowRight, + reinitialiseInterval, originalPadding, originalPaddingTotalWidth, previousContentWidth, + wasAtTop = true, wasAtLeft = true, wasAtBottom = false, wasAtRight = false, + originalElement = elem.clone(false, false).empty(), + mwEvent = $.fn.mwheelIntent ? 'mwheelIntent.jsp' : 'mousewheel.jsp'; + + originalPadding = elem.css('paddingTop') + ' ' + + elem.css('paddingRight') + ' ' + + elem.css('paddingBottom') + ' ' + + elem.css('paddingLeft'); + originalPaddingTotalWidth = (parseInt(elem.css('paddingLeft'), 10) || 0) + + (parseInt(elem.css('paddingRight'), 10) || 0); + + function initialise(s) { + + var /*firstChild, lastChild, */isMaintainingPositon, lastContentX, lastContentY, + hasContainingSpaceChanged, originalScrollTop, originalScrollLeft, + maintainAtBottom = false, maintainAtRight = false; + + settings = s; + + if (pane === undefined) { + originalScrollTop = elem.scrollTop(); + originalScrollLeft = elem.scrollLeft(); + + elem.css( + { + overflow: 'hidden', + padding: 0 + } + ); + // TODO: Deal with where width/ height is 0 as it probably means the element is hidden and we should + // come back to it later and check once it is unhidden... + paneWidth = elem.innerWidth() + originalPaddingTotalWidth; + paneHeight = elem.innerHeight(); + + elem.width(paneWidth); + + pane = $('
      ').css('padding', originalPadding).append(elem.children()); + container = $('
      ') + .css({ + 'width': paneWidth + 'px', + 'height': paneHeight + 'px' + } + ).append(pane).appendTo(elem); + + /* + // Move any margins from the first and last children up to the container so they can still + // collapse with neighbouring elements as they would before jScrollPane + firstChild = pane.find(':first-child'); + lastChild = pane.find(':last-child'); + elem.css( + { + 'margin-top': firstChild.css('margin-top'), + 'margin-bottom': lastChild.css('margin-bottom') + } + ); + firstChild.css('margin-top', 0); + lastChild.css('margin-bottom', 0); + */ + } else { + elem.css('width', ''); + + maintainAtBottom = settings.stickToBottom && isCloseToBottom(); + maintainAtRight = settings.stickToRight && isCloseToRight(); + + hasContainingSpaceChanged = elem.innerWidth() + originalPaddingTotalWidth != paneWidth || elem.outerHeight() != paneHeight; + + if (hasContainingSpaceChanged) { + paneWidth = elem.innerWidth() + originalPaddingTotalWidth; + paneHeight = elem.innerHeight(); + container.css({ + width: paneWidth + 'px', + height: paneHeight + 'px' + }); + } + + // If nothing changed since last check... + if (!hasContainingSpaceChanged && previousContentWidth == contentWidth && pane.outerHeight() == contentHeight) { + elem.width(paneWidth); + return; + } + previousContentWidth = contentWidth; + + pane.css('width', ''); + elem.width(paneWidth); + + container.find('>.jspVerticalBar,>.jspHorizontalBar').remove().end(); + } + + pane.css('overflow', 'auto'); + if (s.contentWidth) { + contentWidth = s.contentWidth; + } else { + contentWidth = pane[0].scrollWidth; + } + contentHeight = pane[0].scrollHeight; + pane.css('overflow', ''); + + percentInViewH = contentWidth / paneWidth; + percentInViewV = contentHeight / paneHeight; + isScrollableV = percentInViewV > 1; + + isScrollableH = percentInViewH > 1; + + if (!(isScrollableH || isScrollableV)) { + elem.removeClass('jspScrollable'); + pane.css({ + top: 0, + width: container.width() - originalPaddingTotalWidth + }); + removeMousewheel(); + removeFocusHandler(); + removeKeyboardNav(); + removeClickOnTrack(); + } else { + elem.addClass('jspScrollable'); + + isMaintainingPositon = settings.maintainPosition && (verticalDragPosition || horizontalDragPosition); + if (isMaintainingPositon) { + lastContentX = contentPositionX(); + lastContentY = contentPositionY(); + } + + initialiseVerticalScroll(); + initialiseHorizontalScroll(); + resizeScrollbars(); + + if (isMaintainingPositon) { + scrollToX(maintainAtRight ? (contentWidth - paneWidth) : lastContentX, false); + scrollToY(maintainAtBottom ? (contentHeight - paneHeight) : lastContentY, false); + } + + initFocusHandler(); + initMousewheel(); + initTouch(); + + if (settings.enableKeyboardNavigation) { + initKeyboardNav(); + } + if (settings.clickOnTrack) { + initClickOnTrack(); + } + + observeHash(); + if (settings.hijackInternalLinks) { + hijackInternalLinks(); + } + } + + if (settings.autoReinitialise && !reinitialiseInterval) { + reinitialiseInterval = setInterval( + function () { + initialise(settings); + }, + settings.autoReinitialiseDelay + ); + } else if (!settings.autoReinitialise && reinitialiseInterval) { + clearInterval(reinitialiseInterval); + } + + originalScrollTop && elem.scrollTop(0) && scrollToY(originalScrollTop, false); + originalScrollLeft && elem.scrollLeft(0) && scrollToX(originalScrollLeft, false); + + elem.trigger('jsp-initialised', [isScrollableH || isScrollableV]); + } + + function initialiseVerticalScroll() { + if (isScrollableV) { + + container.append( + $('
      ').append( + $('
      '), + $('
      ').append( + $('
      ').append( + $('
      '), + $('
      ') + ) + ), + $('
      ') + ) + ); + + verticalBar = container.find('>.jspVerticalBar'); + verticalTrack = verticalBar.find('>.jspTrack'); + verticalDrag = verticalTrack.find('>.jspDrag'); + + if (settings.showArrows) { + arrowUp = $('').on( + 'mousedown.jsp', getArrowScroll(0, -1) + ).on('click.jsp', nil); + arrowDown = $('').on( + 'mousedown.jsp', getArrowScroll(0, 1) + ).on('click.jsp', nil); + if (settings.arrowScrollOnHover) { + arrowUp.on('mouseover.jsp', getArrowScroll(0, -1, arrowUp)); + arrowDown.on('mouseover.jsp', getArrowScroll(0, 1, arrowDown)); + } + + appendArrows(verticalTrack, settings.verticalArrowPositions, arrowUp, arrowDown); + } + + verticalTrackHeight = paneHeight; + container.find('>.jspVerticalBar>.jspCap:visible,>.jspVerticalBar>.jspArrow').each( + function () { + verticalTrackHeight -= $(this).outerHeight(); + } + ); + + + verticalDrag.hover( + function () { + verticalDrag.addClass('jspHover'); + }, + function () { + verticalDrag.removeClass('jspHover'); + } + ).on( + 'mousedown.jsp', + function (e) { + // Stop IE from allowing text selection + $('html').on('dragstart.jsp selectstart.jsp', nil); + + verticalDrag.addClass('jspActive'); + + var startY = e.pageY - verticalDrag.position().top; + + $('html').on( + 'mousemove.jsp', + function (e) { + positionDragY(e.pageY - startY, false); + } + ).on('mouseup.jsp mouseleave.jsp', cancelDrag); + return false; + } + ); + sizeVerticalScrollbar(); + } + } + + function sizeVerticalScrollbar() { + verticalTrack.height(verticalTrackHeight + 'px'); + verticalDragPosition = 0; + scrollbarWidth = settings.verticalGutter + verticalTrack.outerWidth(); + + // Make the pane thinner to allow for the vertical scrollbar + pane.width(paneWidth - scrollbarWidth - originalPaddingTotalWidth); + + // Add margin to the left of the pane if scrollbars are on that side (to position + // the scrollbar on the left or right set it's left or right property in CSS) + try { + if (verticalBar.position().left === 0) { + pane.css('margin-left', scrollbarWidth + 'px'); + } + } catch (err) { + } + } + + function initialiseHorizontalScroll() { + if (isScrollableH) { + + container.append( + $('
      ').append( + $('
      '), + $('
      ').append( + $('
      ').append( + $('
      '), + $('
      ') + ) + ), + $('
      ') + ) + ); + + horizontalBar = container.find('>.jspHorizontalBar'); + horizontalTrack = horizontalBar.find('>.jspTrack'); + horizontalDrag = horizontalTrack.find('>.jspDrag'); + + if (settings.showArrows) { + arrowLeft = $('').on( + 'mousedown.jsp', getArrowScroll(-1, 0) + ).on('click.jsp', nil); + arrowRight = $('').on( + 'mousedown.jsp', getArrowScroll(1, 0) + ).on('click.jsp', nil); + if (settings.arrowScrollOnHover) { + arrowLeft.on('mouseover.jsp', getArrowScroll(-1, 0, arrowLeft)); + arrowRight.on('mouseover.jsp', getArrowScroll(1, 0, arrowRight)); + } + appendArrows(horizontalTrack, settings.horizontalArrowPositions, arrowLeft, arrowRight); + } + + horizontalDrag.hover( + function () { + horizontalDrag.addClass('jspHover'); + }, + function () { + horizontalDrag.removeClass('jspHover'); + } + ).on( + 'mousedown.jsp', + function (e) { + // Stop IE from allowing text selection + $('html').on('dragstart.jsp selectstart.jsp', nil); + + horizontalDrag.addClass('jspActive'); + + var startX = e.pageX - horizontalDrag.position().left; + + $('html').on( + 'mousemove.jsp', + function (e) { + positionDragX(e.pageX - startX, false); + } + ).on('mouseup.jsp mouseleave.jsp', cancelDrag); + return false; + } + ); + horizontalTrackWidth = container.innerWidth(); + sizeHorizontalScrollbar(); + } + } + + function sizeHorizontalScrollbar() { + container.find('>.jspHorizontalBar>.jspCap:visible,>.jspHorizontalBar>.jspArrow').each( + function () { + horizontalTrackWidth -= $(this).outerWidth(); + } + ); + + horizontalTrack.width(horizontalTrackWidth + 'px'); + horizontalDragPosition = 0; + } + + function resizeScrollbars() { + if (isScrollableH && isScrollableV) { + var horizontalTrackHeight = horizontalTrack.outerHeight(), + verticalTrackWidth = verticalTrack.outerWidth(); + verticalTrackHeight -= horizontalTrackHeight; + $(horizontalBar).find('>.jspCap:visible,>.jspArrow').each( + function () { + horizontalTrackWidth += $(this).outerWidth(); + } + ); + horizontalTrackWidth -= verticalTrackWidth; + paneHeight -= verticalTrackWidth; + paneWidth -= horizontalTrackHeight; + horizontalTrack.parent().append( + $('
      ').css('width', horizontalTrackHeight + 'px') + ); + sizeVerticalScrollbar(); + sizeHorizontalScrollbar(); + } + // reflow content + if (isScrollableH) { + pane.width((container.outerWidth() - originalPaddingTotalWidth) + 'px'); + } + contentHeight = pane.outerHeight(); + percentInViewV = contentHeight / paneHeight; + + if (isScrollableH) { + horizontalDragWidth = Math.ceil(1 / percentInViewH * horizontalTrackWidth); + if (horizontalDragWidth > settings.horizontalDragMaxWidth) { + horizontalDragWidth = settings.horizontalDragMaxWidth; + } else if (horizontalDragWidth < settings.horizontalDragMinWidth) { + horizontalDragWidth = settings.horizontalDragMinWidth; + } + horizontalDrag.width(horizontalDragWidth + 'px'); + dragMaxX = horizontalTrackWidth - horizontalDragWidth; + _positionDragX(horizontalDragPosition); // To update the state for the arrow buttons + } + if (isScrollableV) { + verticalDragHeight = Math.ceil(1 / percentInViewV * verticalTrackHeight); + if (verticalDragHeight > settings.verticalDragMaxHeight) { + verticalDragHeight = settings.verticalDragMaxHeight; + } else if (verticalDragHeight < settings.verticalDragMinHeight) { + verticalDragHeight = settings.verticalDragMinHeight; + } + verticalDrag.height(verticalDragHeight + 'px'); + dragMaxY = verticalTrackHeight - verticalDragHeight; + _positionDragY(verticalDragPosition); // To update the state for the arrow buttons + } + } + + function appendArrows(ele, p, a1, a2) { + var p1 = "before", p2 = "after", aTemp; + + // Sniff for mac... Is there a better way to determine whether the arrows would naturally appear + // at the top or the bottom of the bar? + if (p == "os") { + p = /Mac/.test(navigator.platform) ? "after" : "split"; + } + if (p == p1) { + p2 = p; + } else if (p == p2) { + p1 = p; + aTemp = a1; + a1 = a2; + a2 = aTemp; + } + + ele[p1](a1)[p2](a2); + } + + function getArrowScroll(dirX, dirY, ele) { + return function () { + arrowScroll(dirX, dirY, this, ele); + this.blur(); + return false; + }; + } + + function arrowScroll(dirX, dirY, arrow, ele) { + arrow = $(arrow).addClass('jspActive'); + + var eve, + scrollTimeout, + isFirst = true, + doScroll = function () { + if (dirX !== 0) { + jsp.scrollByX(dirX * settings.arrowButtonSpeed); + } + if (dirY !== 0) { + jsp.scrollByY(dirY * settings.arrowButtonSpeed); + } + scrollTimeout = setTimeout(doScroll, isFirst ? settings.initialDelay : settings.arrowRepeatFreq); + isFirst = false; + }; + + doScroll(); + + eve = ele ? 'mouseout.jsp' : 'mouseup.jsp'; + ele = ele || $('html'); + ele.on( + eve, + function () { + arrow.removeClass('jspActive'); + scrollTimeout && clearTimeout(scrollTimeout); + scrollTimeout = null; + ele.off(eve); + } + ); + } + + function initClickOnTrack() { + removeClickOnTrack(); + if (isScrollableV) { + verticalTrack.on( + 'mousedown.jsp', + function (e) { + if (e.originalTarget === undefined || e.originalTarget == e.currentTarget) { + var clickedTrack = $(this), + offset = clickedTrack.offset(), + direction = e.pageY - offset.top - verticalDragPosition, + scrollTimeout, + isFirst = true, + doScroll = function () { + var offset = clickedTrack.offset(), + pos = e.pageY - offset.top - verticalDragHeight / 2, + contentDragY = paneHeight * settings.scrollPagePercent, + dragY = dragMaxY * contentDragY / (contentHeight - paneHeight); + if (direction < 0) { + if (verticalDragPosition - dragY > pos) { + jsp.scrollByY(-contentDragY); + } else { + positionDragY(pos); + } + } else if (direction > 0) { + if (verticalDragPosition + dragY < pos) { + jsp.scrollByY(contentDragY); + } else { + positionDragY(pos); + } + } else { + cancelClick(); + return; + } + scrollTimeout = setTimeout(doScroll, isFirst ? settings.initialDelay : settings.trackClickRepeatFreq); + isFirst = false; + }, + cancelClick = function () { + scrollTimeout && clearTimeout(scrollTimeout); + scrollTimeout = null; + $(document).off('mouseup.jsp', cancelClick); + }; + doScroll(); + $(document).on('mouseup.jsp', cancelClick); + return false; + } + } + ); + } + + if (isScrollableH) { + horizontalTrack.on( + 'mousedown.jsp', + function (e) { + if (e.originalTarget === undefined || e.originalTarget == e.currentTarget) { + var clickedTrack = $(this), + offset = clickedTrack.offset(), + direction = e.pageX - offset.left - horizontalDragPosition, + scrollTimeout, + isFirst = true, + doScroll = function () { + var offset = clickedTrack.offset(), + pos = e.pageX - offset.left - horizontalDragWidth / 2, + contentDragX = paneWidth * settings.scrollPagePercent, + dragX = dragMaxX * contentDragX / (contentWidth - paneWidth); + if (direction < 0) { + if (horizontalDragPosition - dragX > pos) { + jsp.scrollByX(-contentDragX); + } else { + positionDragX(pos); + } + } else if (direction > 0) { + if (horizontalDragPosition + dragX < pos) { + jsp.scrollByX(contentDragX); + } else { + positionDragX(pos); + } + } else { + cancelClick(); + return; + } + scrollTimeout = setTimeout(doScroll, isFirst ? settings.initialDelay : settings.trackClickRepeatFreq); + isFirst = false; + }, + cancelClick = function () { + scrollTimeout && clearTimeout(scrollTimeout); + scrollTimeout = null; + $(document).off('mouseup.jsp', cancelClick); + }; + doScroll(); + $(document).on('mouseup.jsp', cancelClick); + return false; + } + } + ); + } + } + + function removeClickOnTrack() { + if (horizontalTrack) { + horizontalTrack.off('mousedown.jsp'); + } + if (verticalTrack) { + verticalTrack.off('mousedown.jsp'); + } + } + + function cancelDrag() { + $('html').off('dragstart.jsp selectstart.jsp mousemove.jsp mouseup.jsp mouseleave.jsp'); + + if (verticalDrag) { + verticalDrag.removeClass('jspActive'); + } + if (horizontalDrag) { + horizontalDrag.removeClass('jspActive'); + } + } + + function positionDragY(destY, animate) { + if (!isScrollableV) { + return; + } + if (destY < 0) { + destY = 0; + } else if (destY > dragMaxY) { + destY = dragMaxY; + } + + // can't just check if(animate) because false is a valid value that could be passed in... + if (animate === undefined) { + animate = settings.animateScroll; + } + if (animate) { + jsp.animate(verticalDrag, 'top', destY, _positionDragY); + } else { + verticalDrag.css('top', destY); + _positionDragY(destY); + } + + } + + function _positionDragY(destY) { + if (destY === undefined) { + destY = verticalDrag.position().top; + } + + container.scrollTop(0); + verticalDragPosition = destY; + + var isAtTop = verticalDragPosition === 0, + isAtBottom = verticalDragPosition == dragMaxY, + percentScrolled = destY / dragMaxY, + destTop = -percentScrolled * (contentHeight - paneHeight); + + if (wasAtTop != isAtTop || wasAtBottom != isAtBottom) { + wasAtTop = isAtTop; + wasAtBottom = isAtBottom; + elem.trigger('jsp-arrow-change', [wasAtTop, wasAtBottom, wasAtLeft, wasAtRight]); + } + + updateVerticalArrows(isAtTop, isAtBottom); + pane.css('top', destTop); + elem.trigger('jsp-scroll-y', [-destTop, isAtTop, isAtBottom]).trigger('scroll'); + } + + function positionDragX(destX, animate) { + if (!isScrollableH) { + return; + } + if (destX < 0) { + destX = 0; + } else if (destX > dragMaxX) { + destX = dragMaxX; + } + + if (animate === undefined) { + animate = settings.animateScroll; + } + if (animate) { + jsp.animate(horizontalDrag, 'left', destX, _positionDragX); + } else { + horizontalDrag.css('left', destX); + _positionDragX(destX); + } + } + + function _positionDragX(destX) { + if (destX === undefined) { + destX = horizontalDrag.position().left; + } + + container.scrollTop(0); + horizontalDragPosition = destX; + + var isAtLeft = horizontalDragPosition === 0, + isAtRight = horizontalDragPosition == dragMaxX, + percentScrolled = destX / dragMaxX, + destLeft = -percentScrolled * (contentWidth - paneWidth); + + if (wasAtLeft != isAtLeft || wasAtRight != isAtRight) { + wasAtLeft = isAtLeft; + wasAtRight = isAtRight; + elem.trigger('jsp-arrow-change', [wasAtTop, wasAtBottom, wasAtLeft, wasAtRight]); + } + + updateHorizontalArrows(isAtLeft, isAtRight); + pane.css('left', destLeft); + elem.trigger('jsp-scroll-x', [-destLeft, isAtLeft, isAtRight]).trigger('scroll'); + } + + function updateVerticalArrows(isAtTop, isAtBottom) { + if (settings.showArrows) { + arrowUp[isAtTop ? 'addClass' : 'removeClass']('jspDisabled'); + arrowDown[isAtBottom ? 'addClass' : 'removeClass']('jspDisabled'); + } + } + + function updateHorizontalArrows(isAtLeft, isAtRight) { + if (settings.showArrows) { + arrowLeft[isAtLeft ? 'addClass' : 'removeClass']('jspDisabled'); + arrowRight[isAtRight ? 'addClass' : 'removeClass']('jspDisabled'); + } + } + + function scrollToY(destY, animate) { + var percentScrolled = destY / (contentHeight - paneHeight); + positionDragY(percentScrolled * dragMaxY, animate); + } + + function scrollToX(destX, animate) { + var percentScrolled = destX / (contentWidth - paneWidth); + positionDragX(percentScrolled * dragMaxX, animate); + } + + function scrollToElement(ele, stickToTop, animate) { + var e, eleHeight, eleWidth, eleTop = 0, eleLeft = 0, viewportTop, viewportLeft, maxVisibleEleTop, maxVisibleEleLeft, destY, destX; + + // Legal hash values aren't necessarily legal jQuery selectors so we need to catch any + // errors from the lookup... + try { + e = $(ele); + } catch (err) { + return; + } + eleHeight = e.outerHeight(); + eleWidth = e.outerWidth(); + + container.scrollTop(0); + container.scrollLeft(0); + + // loop through parents adding the offset top of any elements that are relatively positioned between + // the focused element and the jspPane so we can get the true distance from the top + // of the focused element to the top of the scrollpane... + while (!e.is('.jspPane')) { + eleTop += e.position().top; + eleLeft += e.position().left; + e = e.offsetParent(); + if (/^body|html$/i.test(e[0].nodeName)) { + // we ended up too high in the document structure. Quit! + return; + } + } + + viewportTop = contentPositionY(); + maxVisibleEleTop = viewportTop + paneHeight; + if (eleTop < viewportTop || stickToTop) { // element is above viewport + destY = eleTop - settings.verticalGutter; + } else if (eleTop + eleHeight > maxVisibleEleTop) { // element is below viewport + destY = eleTop - paneHeight + eleHeight + settings.verticalGutter; + } + if (destY) { + scrollToY(destY, animate); + } + + viewportLeft = contentPositionX(); + maxVisibleEleLeft = viewportLeft + paneWidth; + if (eleLeft < viewportLeft || stickToTop) { // element is to the left of viewport + destX = eleLeft - settings.horizontalGutter; + } else if (eleLeft + eleWidth > maxVisibleEleLeft) { // element is to the right viewport + destX = eleLeft - paneWidth + eleWidth + settings.horizontalGutter; + } + if (destX) { + scrollToX(destX, animate); + } + + } + + function contentPositionX() { + return -pane.position().left; + } + + function contentPositionY() { + return -pane.position().top; + } + + function isCloseToBottom() { + var scrollableHeight = contentHeight - paneHeight; + return (scrollableHeight > 20) && (scrollableHeight - contentPositionY() < 10); + } + + function isCloseToRight() { + var scrollableWidth = contentWidth - paneWidth; + return (scrollableWidth > 20) && (scrollableWidth - contentPositionX() < 10); + } + + function initMousewheel() { + container.off(mwEvent).on( + mwEvent, + function (event, delta, deltaX, deltaY) { + var dX = horizontalDragPosition, dY = verticalDragPosition; + jsp.scrollBy(deltaX * settings.mouseWheelSpeed, -deltaY * settings.mouseWheelSpeed, false); + // return true if there was no movement so rest of screen can scroll + return dX == horizontalDragPosition && dY == verticalDragPosition; + } + ); + } + + function removeMousewheel() { + container.off(mwEvent); + } + + function nil() { + return false; + } + + function initFocusHandler() { + pane.find(':input,a').off('focus.jsp').on( + 'focus.jsp', + function (e) { + scrollToElement(e.target, false); + } + ); + } + + function removeFocusHandler() { + pane.find(':input,a').off('focus.jsp'); + } + + function initKeyboardNav() { + var keyDown, elementHasScrolled, validParents = []; + isScrollableH && validParents.push(horizontalBar[0]); + isScrollableV && validParents.push(verticalBar[0]); + + // IE also focuses elements that don't have tabindex set. + pane.focus( + function () { + elem.focus(); + } + ); + + elem.attr('tabindex', 0) + .off('keydown.jsp keypress.jsp') + .on( + 'keydown.jsp', + function (e) { + if (e.target !== this && !(validParents.length && $(e.target).closest(validParents).length)) { + return; + } + var dX = horizontalDragPosition, dY = verticalDragPosition; + switch (e.keyCode) { + case 40: // down + case 38: // up + case 34: // page down + case 32: // space + case 33: // page up + case 39: // right + case 37: // left + keyDown = e.keyCode; + keyDownHandler(); + break; + case 35: // end + scrollToY(contentHeight - paneHeight); + keyDown = null; + break; + case 36: // home + scrollToY(0); + keyDown = null; + break; + } + + elementHasScrolled = e.keyCode == keyDown && dX != horizontalDragPosition || dY != verticalDragPosition; + return !elementHasScrolled; + } + ).off( + 'keypress.jsp', // For FF/ OSX so that we can cancel the repeat key presses if the JSP scrolls... + function (e) { + if (e.keyCode == keyDown) { + keyDownHandler(); + } + return !elementHasScrolled; + } + ); + + if (settings.hideFocus) { + elem.css('outline', 'none'); + if ('hideFocus' in container[0]) { + elem.attr('hideFocus', true); + } + } else { + elem.css('outline', ''); + if ('hideFocus' in container[0]) { + elem.attr('hideFocus', false); + } + } + + function keyDownHandler() { + var dX = horizontalDragPosition, dY = verticalDragPosition; + switch (keyDown) { + case 40: // down + jsp.scrollByY(settings.keyboardSpeed, false); + break; + case 38: // up + jsp.scrollByY(-settings.keyboardSpeed, false); + break; + case 34: // page down + case 32: // space + jsp.scrollByY(paneHeight * settings.scrollPagePercent, false); + break; + case 33: // page up + jsp.scrollByY(-paneHeight * settings.scrollPagePercent, false); + break; + case 39: // right + jsp.scrollByX(settings.keyboardSpeed, false); + break; + case 37: // left + jsp.scrollByX(-settings.keyboardSpeed, false); + break; + } + + elementHasScrolled = dX != horizontalDragPosition || dY != verticalDragPosition; + return elementHasScrolled; + } + } + + function removeKeyboardNav() { + elem.attr('tabindex', '-1') + .removeAttr('tabindex') + .off('keydown.jsp keypress.jsp'); + } + + function observeHash() { + if (location.hash && location.hash.length > 1) { + var e, + retryInt, + hash = escape(location.hash.substr(1)) // hash must be escaped to prevent XSS + ; + try { + e = $('#' + hash + ', a[name="' + hash + '"]'); + } catch (err) { + return; + } + + if (e.length && pane.find(hash)) { + // nasty workaround but it appears to take a little while before the hash has done its thing + // to the rendered page so we just wait until the container's scrollTop has been messed up. + if (container.scrollTop() === 0) { + retryInt = setInterval( + function () { + if (container.scrollTop() > 0) { + scrollToElement(e, true); + $(document).scrollTop(container.position().top); + clearInterval(retryInt); + } + }, + 50 + ); + } else { + scrollToElement(e, true); + $(document).scrollTop(container.position().top); + } + } + } + } + + function hijackInternalLinks() { + // only register the link handler once + if ($(document.body).data('jspHijack')) { + return; + } + + // remember that the handler was bound + $(document.body).data('jspHijack', true); + + // use live handler to also capture newly created links + $(document.body).delegate('a[href*=#]', 'click', function (event) { + // does the link point to the same page? + // this also takes care of cases with a -Tag or Links not starting with the hash # + // e.g. when the current url already is index.html + var href = this.href.substr(0, this.href.indexOf('#')), + locationHref = location.href, + hash, + element, + container, + jsp, + scrollTop, + elementTop; + if (location.href.indexOf('#') !== -1) { + locationHref = location.href.substr(0, location.href.indexOf('#')); + } + if (href !== locationHref) { + // the link points to another page + return; + } + + // check if jScrollPane should handle this click event + hash = escape(this.href.substr(this.href.indexOf('#') + 1)); + + // find the element on the page + element; + try { + element = $('#' + hash + ', a[name="' + hash + '"]'); + } catch (e) { + // hash is not a valid jQuery identifier + return; + } + + if (!element.length) { + // this link does not point to an element on this page + return; + } + + container = element.closest('.jspScrollable'); + jsp = container.data('jsp'); + + // jsp might be another jsp instance than the one, that bound this event + // remember: this event is only bound once for all instances. + jsp.scrollToElement(element, true); + + if (container[0].scrollIntoView) { + // also scroll to the top of the container (if it is not visible) + scrollTop = $(window).scrollTop(); + elementTop = element.offset().top; + if (elementTop < scrollTop || elementTop > scrollTop + $(window).height()) { + container[0].scrollIntoView(); + } + } + + // jsp handled this event, prevent the browser default (scrolling :P) + event.preventDefault(); + }); + } + + // Init touch on iPad, iPhone, iPod, Android + function initTouch() { + var startX, + startY, + touchStartX, + touchStartY, + moved, + moving = false; + + container.off('touchstart.jsp touchmove.jsp touchend.jsp click.jsp-touchclick').on( + 'touchstart.jsp', + function (e) { + var touch = e.originalEvent.touches[0]; + startX = contentPositionX(); + startY = contentPositionY(); + touchStartX = touch.pageX; + touchStartY = touch.pageY; + moved = false; + moving = true; + } + ).on( + 'touchmove.jsp', + function (ev) { + if (!moving) { + return; + } + + var touchPos = ev.originalEvent.touches[0], + dX = horizontalDragPosition, dY = verticalDragPosition; + + jsp.scrollTo(startX + touchStartX - touchPos.pageX, startY + touchStartY - touchPos.pageY); + + moved = moved || Math.abs(touchStartX - touchPos.pageX) > 5 || Math.abs(touchStartY - touchPos.pageY) > 5; + + // return true if there was no movement so rest of screen can scroll + return dX == horizontalDragPosition && dY == verticalDragPosition; + } + ).on( + 'touchend.jsp', + function (e) { + moving = false; + /*if(moved) { + return false; + }*/ + } + ).on( + 'click.jsp-touchclick', + function (e) { + if (moved) { + moved = false; + return false; + } + } + ); + } + + function destroy() { + var currentY = contentPositionY(), + currentX = contentPositionX(); + elem.removeClass('jspScrollable').off('.jsp'); + elem.replaceWith(originalElement.append(pane.children())); + originalElement.scrollTop(currentY); + originalElement.scrollLeft(currentX); + + // clear reinitialize timer if active + if (reinitialiseInterval) { + clearInterval(reinitialiseInterval); + } + } + + // Public API + $.extend( + jsp, + { + // Reinitialises the scroll pane (if it's internal dimensions have changed since the last time it + // was initialised). The settings object which is passed in will override any settings from the + // previous time it was initialised - if you don't pass any settings then the ones from the previous + // initialisation will be used. + reinitialise: function (s) { + s = $.extend({}, settings, s); + initialise(s); + }, + // Scrolls the specified element (a jQuery object, DOM node or jQuery selector string) into view so + // that it can be seen within the viewport. If stickToTop is true then the element will appear at + // the top of the viewport, if it is false then the viewport will scroll as little as possible to + // show the element. You can also specify if you want animation to occur. If you don't provide this + // argument then the animateScroll value from the settings object is used instead. + scrollToElement: function (ele, stickToTop, animate) { + scrollToElement(ele, stickToTop, animate); + }, + // Scrolls the pane so that the specified co-ordinates within the content are at the top left + // of the viewport. animate is optional and if not passed then the value of animateScroll from + // the settings object this jScrollPane was initialised with is used. + scrollTo: function (destX, destY, animate) { + scrollToX(destX, animate); + scrollToY(destY, animate); + }, + // Scrolls the pane so that the specified co-ordinate within the content is at the left of the + // viewport. animate is optional and if not passed then the value of animateScroll from the settings + // object this jScrollPane was initialised with is used. + scrollToX: function (destX, animate) { + scrollToX(destX, animate); + }, + // Scrolls the pane so that the specified co-ordinate within the content is at the top of the + // viewport. animate is optional and if not passed then the value of animateScroll from the settings + // object this jScrollPane was initialised with is used. + scrollToY: function (destY, animate) { + scrollToY(destY, animate); + }, + // Scrolls the pane to the specified percentage of its maximum horizontal scroll position. animate + // is optional and if not passed then the value of animateScroll from the settings object this + // jScrollPane was initialised with is used. + scrollToPercentX: function (destPercentX, animate) { + scrollToX(destPercentX * (contentWidth - paneWidth), animate); + }, + // Scrolls the pane to the specified percentage of its maximum vertical scroll position. animate + // is optional and if not passed then the value of animateScroll from the settings object this + // jScrollPane was initialised with is used. + scrollToPercentY: function (destPercentY, animate) { + scrollToY(destPercentY * (contentHeight - paneHeight), animate); + }, + // Scrolls the pane by the specified amount of pixels. animate is optional and if not passed then + // the value of animateScroll from the settings object this jScrollPane was initialised with is used. + scrollBy: function (deltaX, deltaY, animate) { + jsp.scrollByX(deltaX, animate); + jsp.scrollByY(deltaY, animate); + }, + // Scrolls the pane by the specified amount of pixels. animate is optional and if not passed then + // the value of animateScroll from the settings object this jScrollPane was initialised with is used. + scrollByX: function (deltaX, animate) { + var destX = contentPositionX() + Math[deltaX < 0 ? 'floor' : 'ceil'](deltaX), + percentScrolled = destX / (contentWidth - paneWidth); + positionDragX(percentScrolled * dragMaxX, animate); + }, + // Scrolls the pane by the specified amount of pixels. animate is optional and if not passed then + // the value of animateScroll from the settings object this jScrollPane was initialised with is used. + scrollByY: function (deltaY, animate) { + var destY = contentPositionY() + Math[deltaY < 0 ? 'floor' : 'ceil'](deltaY), + percentScrolled = destY / (contentHeight - paneHeight); + positionDragY(percentScrolled * dragMaxY, animate); + }, + // Positions the horizontal drag at the specified x position (and updates the viewport to reflect + // this). animate is optional and if not passed then the value of animateScroll from the settings + // object this jScrollPane was initialised with is used. + positionDragX: function (x, animate) { + positionDragX(x, animate); + }, + // Positions the vertical drag at the specified y position (and updates the viewport to reflect + // this). animate is optional and if not passed then the value of animateScroll from the settings + // object this jScrollPane was initialised with is used. + positionDragY: function (y, animate) { + positionDragY(y, animate); + }, + // This method is called when jScrollPane is trying to animate to a new position. You can override + // it if you want to provide advanced animation functionality. It is passed the following arguments: + // * ele - the element whose position is being animated + // * prop - the property that is being animated + // * value - the value it's being animated to + // * stepCallback - a function that you must execute each time you update the value of the property + // You can use the default implementation (below) as a starting point for your own implementation. + animate: function (ele, prop, value, stepCallback) { + var params = {}; + params[prop] = value; + ele.animate( + params, + { + 'duration': settings.animateDuration, + 'easing': settings.animateEase, + 'queue': false, + 'step': stepCallback + } + ); + }, + // Returns the current x position of the viewport with regards to the content pane. + getContentPositionX: function () { + return contentPositionX(); + }, + // Returns the current y position of the viewport with regards to the content pane. + getContentPositionY: function () { + return contentPositionY(); + }, + // Returns the width of the content within the scroll pane. + getContentWidth: function () { + return contentWidth; + }, + // Returns the height of the content within the scroll pane. + getContentHeight: function () { + return contentHeight; + }, + // Returns the horizontal position of the viewport within the pane content. + getPercentScrolledX: function () { + return contentPositionX() / (contentWidth - paneWidth); + }, + // Returns the vertical position of the viewport within the pane content. + getPercentScrolledY: function () { + return contentPositionY() / (contentHeight - paneHeight); + }, + // Returns whether or not this scrollpane has a horizontal scrollbar. + getIsScrollableH: function () { + return isScrollableH; + }, + // Returns whether or not this scrollpane has a vertical scrollbar. + getIsScrollableV: function () { + return isScrollableV; + }, + // Gets a reference to the content pane. It is important that you use this method if you want to + // edit the content of your jScrollPane as if you access the element directly then you may have some + // problems (as your original element has had additional elements for the scrollbars etc added into + // it). + getContentPane: function () { + return pane; + }, + // Scrolls this jScrollPane down as far as it can currently scroll. If animate isn't passed then the + // animateScroll value from settings is used instead. + scrollToBottom: function (animate) { + positionDragY(dragMaxY, animate); + }, + // Hijacks the links on the page which link to content inside the scrollpane. If you have changed + // the content of your page (e.g. via AJAX) and want to make sure any new anchor links to the + // contents of your scroll pane will work then call this function. + hijackInternalLinks: $.noop, + // Removes the jScrollPane and returns the page to the state it was in before jScrollPane was + // initialised. + destroy: function () { + destroy(); + } + } + ); + + initialise(s); + } + + // Pluginifying code... + settings = $.extend({}, $.fn.jScrollPane.defaults, settings); + + // Apply default speed + $.each(['mouseWheelSpeed', 'arrowButtonSpeed', 'trackClickSpeed', 'keyboardSpeed'], function () { + settings[this] = settings[this] || settings.speed; + }); + + return this.each( + function () { + var elem = $(this), jspApi = elem.data('jsp'); + if (jspApi) { + jspApi.reinitialise(settings); + } else { + $("script", elem).filter('[type="text/javascript"], :not([type])').remove(); + jspApi = new JScrollPane(elem, settings); + elem.data('jsp', jspApi); + } + } + ); + }; + + $.fn.jScrollPane.defaults = { + showArrows: false, + maintainPosition: true, + stickToBottom: false, + stickToRight: false, + clickOnTrack: true, + autoReinitialise: false, + autoReinitialiseDelay: 500, + verticalDragMinHeight: 30, + verticalDragMaxHeight: 99999, + horizontalDragMinWidth: 30, + horizontalDragMaxWidth: 99999, + contentWidth: undefined, + animateScroll: false, + animateDuration: 300, + animateEase: 'linear', + hijackInternalLinks: false, + verticalGutter: 4, + horizontalGutter: 4, + mouseWheelSpeed: 0, + arrowButtonSpeed: 0, + arrowRepeatFreq: 50, + arrowScrollOnHover: false, + trackClickSpeed: 0, + trackClickRepeatFreq: 70, + verticalArrowPositions: 'split', + horizontalArrowPositions: 'split', + enableKeyboardNavigation: true, + hideFocus: false, + keyboardSpeed: 0, + initialDelay: 300, // Delay before starting repeating + speed: 30, // Default speed when others falsey + scrollPagePercent: .8 // Percent of visible area scrolled when pageUp/Down or track area pressed + }; + +})(jQuery); + +(function ($) { + $.fn.dnnSettingDropdown = function () { + var clicked = function () { + if ($(this).hasClass('dnnButtonDropdown')) { + $(this).removeClass('dnnButtonDropdown').addClass('dnnButtonDropdown-clicked'); + $(this).next().show(); + } + }; + + var hideDropdown = function () { + var btn = $(this).children(':first'); + if (btn.hasClass('dnnButtonDropdown-clicked')) { + btn.removeClass('dnnButtonDropdown-clicked').addClass('dnnButtonDropdown'); + btn.next().fadeOut(); + } + }; + + var hoverConfig = { + over: function () { + }, + out: hideDropdown, + timout: 600 + }; + + return $(this).each(function () { + $(this).off('click', clicked).on('click', clicked); + $(this).parent().hoverIntent(hoverConfig); + }); + }; +})(jQuery); + +(function ($) { + $.fn.onEnter = function (fn) { + return this.each(function () { + var $this = $(this); + $this.on('onEnter', fn); + $this.keydown(function (e) { + if ((e.which && e.which === 13) || (e.keyCode && e.keyCode === 13)) { + e.preventDefault(); + e.stopPropagation(); + $this.trigger('onEnter'); + } + }); + }); + }; +})(jQuery); + +(function ($) { + $.extend({ + onAjaxError: function (jqXhr, textStatus, errorThrown) { + var title, text; + if (jqXhr && jqXhr.status === 401) { + dnnModal.show('../Login.aspx' + '?popUp=true', true, 300, 650, true, ''); + return; + } + if (jqXhr && jqXhr.responseText && jqXhr.statusText) { + try { + title = jqXhr.statusText + " (" + jqXhr.status + ")"; + text = JSON.parse(jqXhr.responseText).Message; + } + catch (e) { + text = errorThrown; + } + } + $.dnnAlert({ title: title || "Error", text: text || "Unknown error" }); + } + }); +})(jQuery); + +(function ($) { + $.fn.dnnSliderInput = function (options) { + var sliderOptions = $.extend({}, $.fn.dnnSliderInput.defaults, options); + return $(this).each(function () { + var $this = $(this); + var value = $this.val(); + var $slider = $('
      '); + $this.hide().after($slider); + + $slider.slider(sliderOptions); + $slider.slider('value', value); + + var $tooltip = $(''); + + var calcTooltipPosition = function () { + setTimeout(function() { + var left = $slider.find('.ui-slider-handle')[0].style.left; + $tooltip.css('left', left); + }, 0); + }; + + $tooltip.find('.dnnHelpText').html(value); + $tooltip.data('initialized', true); + $slider.append($tooltip); + + calcTooltipPosition(); + $slider.on('slide', function(event, ui) { + $tooltip.find('.dnnHelpText').html(ui.value); + $this.val(ui.value); + calcTooltipPosition(); + }); + }); + }; + + $.fn.dnnSliderInput.defaults = { + min: 0, + max: 100, + step: 1 + } +})(jQuery); + +// please keep this func at last of this file, thanks +(function ($) { + /* Start customised controls */ + var inputFocusFix = function () { + var errorMsg = $(this).next(); + if (errorMsg.hasClass('dnnFormError')) + errorMsg.hide(); + }; + var throttle = null; + var dnnInitCustomisedCtrls = function () { + if (throttle != null) { + clearTimeout(throttle); + throttle = null; + } + throttle = setTimeout(function () { + $('.dnnForm input[type="checkbox"]').dnnCheckbox(); + $('.dnnForm input[type="radio"]').dnnCheckbox({ cls: 'dnnRadiobutton' }); + $('.dnnTooltip').dnnTooltip(); + $('.dnnForm input[type="text"], .dnnForm input[type="password"]').off('focus', inputFocusFix).on('focus', inputFocusFix); + $('.dnnForm :file').dnnFileInput(); + $('.dnnForm input[data-default]').dnnPlaceholder(); + }, 200); + //change the window confirm style to DNN style + $("*[onclick*='return confirm']").each(function () { + var instance = $(this); + var isButton = this.nodeName.toLowerCase() == "img" || this.nodeName.toLowerCase() == "input"; + var script = /return confirm\((['"])([\s\S]*?)\1\)/g.exec(instance.attr("onclick")); + if (script != null) { + var confirmContent = script[2].split("\\" + script[1]).join(script[1]); + //restore unicode chars. + confirmContent = confirmContent.replace(/\\u([\d\w]{4})/gi, function(match, charCode) { + return String.fromCharCode(parseInt(charCode, 16)); + }); + instance.attr("onclick", instance.attr("onclick").replace(script[0], "void(0)")).dnnConfirm({ + text: confirmContent, + isButton: isButton + }); + } + }); + }; + var saveRgDataDivScrollTop = function () { + window.__rgDataDivScrollTopPersistArray = []; + $('.rgDataDiv').each(function () { + var $this = $(this); + var ele = $this.get(0); + if (ele.scrollPane) { + var api = ele.scrollPane.data('jsp'); + var y = api.getContentPositionY(); + window.__rgDataDivScrollTopPersistArray.push(y); + } + }); + }; + + var handlerSendVerificationMailLink = function() { + $(document.body).on('click', 'a.send-verification-mail', function(e) { + e.preventDefault(); + + var service = $.dnnSF(); + var url = service.getServiceRoot('InternalServices') + 'NewUserNotificationService/SendVerificationMail'; + var antiForgeryToken = $('input[name="__RequestVerificationToken"]').val(); + url += '?__RequestVerificationToken=' + antiForgeryToken; + + $.ajax({ + url: url, + beforeSend: service ? service.setModuleHeaders : null, + success: function(data) { + $.dnnAlert({ text: data.Result }); + }, + error: function (xhr, textStatus, errorThrown) { + if (xhr && xhr.responseText) { + $.dnnAlert({ text: JSON.parse(xhr.responseText).Message }); + } + }, + type: 'POST', + dataType: 'json', + contentType: "application/json" + }); + }); + }; + + window.__rgDataDivScrollTopPersistArray = []; + $(document).ajaxComplete(dnnInitCustomisedCtrls); + Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(saveRgDataDivScrollTop); + Sys.WebForms.PageRequestManager.getInstance().add_endRequest(dnnInitCustomisedCtrls); + $(dnnInitCustomisedCtrls); + handlerSendVerificationMailLink(); +})(jQuery); \ No newline at end of file diff --git a/DNN Platform/JavaScript Libraries/DnnPlugins/releaseNotes.txt b/DNN Platform/JavaScript Libraries/DnnPlugins/releaseNotes.txt new file mode 100644 index 00000000000..e69de29bb2d diff --git a/DNN Platform/JavaScript Libraries/HoverIntent/HoverIntent.dnn b/DNN Platform/JavaScript Libraries/HoverIntent/HoverIntent.dnn new file mode 100644 index 00000000000..d2705466a24 --- /dev/null +++ b/DNN Platform/JavaScript Libraries/HoverIntent/HoverIntent.dnn @@ -0,0 +1,39 @@ + + + + hoverIntent jQuery Plugin + hoverIntent is a plug-in that attempts to determine the user's intent… like a crystal ball, only with mouse movement! + Icons\Sigma\Extensions_32x32_Standard.png + + .NET Foundation and Contributors + DNN Community + https://dnncommunity.org + info@dnncommunity.org + + + + true + + jQuery + + + + + HoverIntent + jquery.hoverIntent.min.js + jQuery.fn.hoverIntent + https://cdnjs.cloudflare.com/ajax/libs/jquery.hoverintent/1.10.1/jquery.hoverIntent.min.js + + + + + HoverIntent + + jquery.hoverIntent.min.js + + + + + + + diff --git a/DNN Platform/JavaScript Libraries/HoverIntent/LICENSE.txt b/DNN Platform/JavaScript Libraries/HoverIntent/LICENSE.txt new file mode 100644 index 00000000000..5dd45bf6728 --- /dev/null +++ b/DNN Platform/JavaScript Libraries/HoverIntent/LICENSE.txt @@ -0,0 +1,20 @@ +MIT License + +Copyright 2010 Sebastian Tschan, https://blueimp.net + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/DNN Platform/JavaScript Libraries/HoverIntent/jquery.hoverIntent.min.js b/DNN Platform/JavaScript Libraries/HoverIntent/jquery.hoverIntent.min.js new file mode 100644 index 00000000000..8626550abd7 --- /dev/null +++ b/DNN Platform/JavaScript Libraries/HoverIntent/jquery.hoverIntent.min.js @@ -0,0 +1,9 @@ +/*! + * hoverIntent v1.10.1 // 2019.10.05 // jQuery v1.7.0+ + * http://briancherne.github.io/jquery-hoverIntent/ + * + * You may use hoverIntent under the terms of the MIT license. Basically that + * means you are free to use hoverIntent as long as this header is left intact. + * Copyright 2007-2019 Brian Cherne + */ +!function(factory){"use strict";"function"==typeof define&&define.amd?define(["jquery"],factory):"object"==typeof module&&module.exports?module.exports=factory(require("jquery")):jQuery&&!jQuery.fn.hoverIntent&&factory(jQuery)}(function($){"use strict";function track(ev){cX=ev.pageX,cY=ev.pageY}var cX,cY,_cfg={interval:100,sensitivity:6,timeout:0},INSTANCE_COUNT=0,compare=function(ev,$el,s,cfg){if(Math.sqrt((s.pX-cX)*(s.pX-cX)+(s.pY-cY)*(s.pY-cY)) + + + jQuery File Upload Plugin + File Upload widget with multiple file selection, drag&drop support, progress bars, validation and preview images, audio and video for jQuery. + Icons\Sigma\Extensions_32x32_Standard.png + + .NET Foundation and Contributors + DNN Community + https://dnncommunity.org + info@dnncommunity.org + + + + true + + jQuery.iframe-transport + jQuery-UI + + + + + jQuery.Fileupload + jquery.fileupload.js + jQuery.fn.fileupload + https://cdnjs.cloudflare.com/ajax/libs/blueimp-file-upload/10.7.0/js/jquery.fileupload.min.js + + + + + jQuery.Fileupload + + jquery.fileupload.js + + + + + + + diff --git a/DNN Platform/JavaScript Libraries/jQuery.Fileupload/jquery.fileupload.js b/DNN Platform/JavaScript Libraries/jQuery.Fileupload/jquery.fileupload.js new file mode 100644 index 00000000000..de4ae1c4981 --- /dev/null +++ b/DNN Platform/JavaScript Libraries/jQuery.Fileupload/jquery.fileupload.js @@ -0,0 +1,1611 @@ +/* + * jQuery File Upload Plugin + * https://github.com/blueimp/jQuery-File-Upload + * + * Copyright 2010, Sebastian Tschan + * https://blueimp.net + * + * Licensed under the MIT license: + * https://opensource.org/licenses/MIT + */ + +/* global define, require */ +/* eslint-disable new-cap */ + +(function (factory) { + 'use strict'; + if (typeof define === 'function' && define.amd) { + // Register as an anonymous AMD module: + define(['jquery', 'jquery.ui.widget'], factory); + } else if (typeof exports === 'object') { + // Node/CommonJS: + factory(require('jquery'), require('./vendor/jquery.ui.widget')); + } else { + // Browser globals: + factory(window.jQuery); + } +})(function ($) { + 'use strict'; + + // Detect file input support, based on + // https://viljamis.com/2012/file-upload-support-on-mobile/ + $.support.fileInput = !( + new RegExp( + // Handle devices which give false positives for the feature detection: + '(Android (1\\.[0156]|2\\.[01]))' + + '|(Windows Phone (OS 7|8\\.0))|(XBLWP)|(ZuneWP)|(WPDesktop)' + + '|(w(eb)?OSBrowser)|(webOS)' + + '|(Kindle/(1\\.0|2\\.[05]|3\\.0))' + ).test(window.navigator.userAgent) || + // Feature detection for all other devices: + $('').prop('disabled') + ); + + // The FileReader API is not actually used, but works as feature detection, + // as some Safari versions (5?) support XHR file uploads via the FormData API, + // but not non-multipart XHR file uploads. + // window.XMLHttpRequestUpload is not available on IE10, so we check for + // window.ProgressEvent instead to detect XHR2 file upload capability: + $.support.xhrFileUpload = !!(window.ProgressEvent && window.FileReader); + $.support.xhrFormDataFileUpload = !!window.FormData; + + // Detect support for Blob slicing (required for chunked uploads): + $.support.blobSlice = + window.Blob && + (Blob.prototype.slice || + Blob.prototype.webkitSlice || + Blob.prototype.mozSlice); + + /** + * Helper function to create drag handlers for dragover/dragenter/dragleave + * + * @param {string} type Event type + * @returns {Function} Drag handler + */ + function getDragHandler(type) { + var isDragOver = type === 'dragover'; + return function (e) { + e.dataTransfer = e.originalEvent && e.originalEvent.dataTransfer; + var dataTransfer = e.dataTransfer; + if ( + dataTransfer && + $.inArray('Files', dataTransfer.types) !== -1 && + this._trigger(type, $.Event(type, { delegatedEvent: e })) !== false + ) { + e.preventDefault(); + if (isDragOver) { + dataTransfer.dropEffect = 'copy'; + } + } + }; + } + + // The fileupload widget listens for change events on file input fields defined + // via fileInput setting and paste or drop events of the given dropZone. + // In addition to the default jQuery Widget methods, the fileupload widget + // exposes the "add" and "send" methods, to add or directly send files using + // the fileupload API. + // By default, files added via file input selection, paste, drag & drop or + // "add" method are uploaded immediately, but it is possible to override + // the "add" callback option to queue file uploads. + $.widget('blueimp.fileupload', { + options: { + // The drop target element(s), by the default the complete document. + // Set to null to disable drag & drop support: + dropZone: $(document), + // The paste target element(s), by the default undefined. + // Set to a DOM node or jQuery object to enable file pasting: + pasteZone: undefined, + // The file input field(s), that are listened to for change events. + // If undefined, it is set to the file input fields inside + // of the widget element on plugin initialization. + // Set to null to disable the change listener. + fileInput: undefined, + // By default, the file input field is replaced with a clone after + // each input field change event. This is required for iframe transport + // queues and allows change events to be fired for the same file + // selection, but can be disabled by setting the following option to false: + replaceFileInput: true, + // The parameter name for the file form data (the request argument name). + // If undefined or empty, the name property of the file input field is + // used, or "files[]" if the file input name property is also empty, + // can be a string or an array of strings: + paramName: undefined, + // By default, each file of a selection is uploaded using an individual + // request for XHR type uploads. Set to false to upload file + // selections in one request each: + singleFileUploads: true, + // To limit the number of files uploaded with one XHR request, + // set the following option to an integer greater than 0: + limitMultiFileUploads: undefined, + // The following option limits the number of files uploaded with one + // XHR request to keep the request size under or equal to the defined + // limit in bytes: + limitMultiFileUploadSize: undefined, + // Multipart file uploads add a number of bytes to each uploaded file, + // therefore the following option adds an overhead for each file used + // in the limitMultiFileUploadSize configuration: + limitMultiFileUploadSizeOverhead: 512, + // Set the following option to true to issue all file upload requests + // in a sequential order: + sequentialUploads: false, + // To limit the number of concurrent uploads, + // set the following option to an integer greater than 0: + limitConcurrentUploads: undefined, + // Set the following option to true to force iframe transport uploads: + forceIframeTransport: false, + // Set the following option to the location of a redirect url on the + // origin server, for cross-domain iframe transport uploads: + redirect: undefined, + // The parameter name for the redirect url, sent as part of the form + // data and set to 'redirect' if this option is empty: + redirectParamName: undefined, + // Set the following option to the location of a postMessage window, + // to enable postMessage transport uploads: + postMessage: undefined, + // By default, XHR file uploads are sent as multipart/form-data. + // The iframe transport is always using multipart/form-data. + // Set to false to enable non-multipart XHR uploads: + multipart: true, + // To upload large files in smaller chunks, set the following option + // to a preferred maximum chunk size. If set to 0, null or undefined, + // or the browser does not support the required Blob API, files will + // be uploaded as a whole. + maxChunkSize: undefined, + // When a non-multipart upload or a chunked multipart upload has been + // aborted, this option can be used to resume the upload by setting + // it to the size of the already uploaded bytes. This option is most + // useful when modifying the options object inside of the "add" or + // "send" callbacks, as the options are cloned for each file upload. + uploadedBytes: undefined, + // By default, failed (abort or error) file uploads are removed from the + // global progress calculation. Set the following option to false to + // prevent recalculating the global progress data: + recalculateProgress: true, + // Interval in milliseconds to calculate and trigger progress events: + progressInterval: 100, + // Interval in milliseconds to calculate progress bitrate: + bitrateInterval: 500, + // By default, uploads are started automatically when adding files: + autoUpload: true, + // By default, duplicate file names are expected to be handled on + // the server-side. If this is not possible (e.g. when uploading + // files directly to Amazon S3), the following option can be set to + // an empty object or an object mapping existing filenames, e.g.: + // { "image.jpg": true, "image (1).jpg": true } + // If it is set, all files will be uploaded with unique filenames, + // adding increasing number suffixes if necessary, e.g.: + // "image (2).jpg" + uniqueFilenames: undefined, + + // Error and info messages: + messages: { + uploadedBytes: 'Uploaded bytes exceed file size' + }, + + // Translation function, gets the message key to be translated + // and an object with context specific data as arguments: + i18n: function (message, context) { + // eslint-disable-next-line no-param-reassign + message = this.messages[message] || message.toString(); + if (context) { + $.each(context, function (key, value) { + // eslint-disable-next-line no-param-reassign + message = message.replace('{' + key + '}', value); + }); + } + return message; + }, + + // Additional form data to be sent along with the file uploads can be set + // using this option, which accepts an array of objects with name and + // value properties, a function returning such an array, a FormData + // object (for XHR file uploads), or a simple object. + // The form of the first fileInput is given as parameter to the function: + formData: function (form) { + return form.serializeArray(); + }, + + // The add callback is invoked as soon as files are added to the fileupload + // widget (via file input selection, drag & drop, paste or add API call). + // If the singleFileUploads option is enabled, this callback will be + // called once for each file in the selection for XHR file uploads, else + // once for each file selection. + // + // The upload starts when the submit method is invoked on the data parameter. + // The data object contains a files property holding the added files + // and allows you to override plugin options as well as define ajax settings. + // + // Listeners for this callback can also be bound the following way: + // .bind('fileuploadadd', func); + // + // data.submit() returns a Promise object and allows to attach additional + // handlers using jQuery's Deferred callbacks: + // data.submit().done(func).fail(func).always(func); + add: function (e, data) { + if (e.isDefaultPrevented()) { + return false; + } + if ( + data.autoUpload || + (data.autoUpload !== false && + $(this).fileupload('option', 'autoUpload')) + ) { + data.process().done(function () { + data.submit(); + }); + } + }, + + // Other callbacks: + + // Callback for the submit event of each file upload: + // submit: function (e, data) {}, // .bind('fileuploadsubmit', func); + + // Callback for the start of each file upload request: + // send: function (e, data) {}, // .bind('fileuploadsend', func); + + // Callback for successful uploads: + // done: function (e, data) {}, // .bind('fileuploaddone', func); + + // Callback for failed (abort or error) uploads: + // fail: function (e, data) {}, // .bind('fileuploadfail', func); + + // Callback for completed (success, abort or error) requests: + // always: function (e, data) {}, // .bind('fileuploadalways', func); + + // Callback for upload progress events: + // progress: function (e, data) {}, // .bind('fileuploadprogress', func); + + // Callback for global upload progress events: + // progressall: function (e, data) {}, // .bind('fileuploadprogressall', func); + + // Callback for uploads start, equivalent to the global ajaxStart event: + // start: function (e) {}, // .bind('fileuploadstart', func); + + // Callback for uploads stop, equivalent to the global ajaxStop event: + // stop: function (e) {}, // .bind('fileuploadstop', func); + + // Callback for change events of the fileInput(s): + // change: function (e, data) {}, // .bind('fileuploadchange', func); + + // Callback for paste events to the pasteZone(s): + // paste: function (e, data) {}, // .bind('fileuploadpaste', func); + + // Callback for drop events of the dropZone(s): + // drop: function (e, data) {}, // .bind('fileuploaddrop', func); + + // Callback for dragover events of the dropZone(s): + // dragover: function (e) {}, // .bind('fileuploaddragover', func); + + // Callback before the start of each chunk upload request (before form data initialization): + // chunkbeforesend: function (e, data) {}, // .bind('fileuploadchunkbeforesend', func); + + // Callback for the start of each chunk upload request: + // chunksend: function (e, data) {}, // .bind('fileuploadchunksend', func); + + // Callback for successful chunk uploads: + // chunkdone: function (e, data) {}, // .bind('fileuploadchunkdone', func); + + // Callback for failed (abort or error) chunk uploads: + // chunkfail: function (e, data) {}, // .bind('fileuploadchunkfail', func); + + // Callback for completed (success, abort or error) chunk upload requests: + // chunkalways: function (e, data) {}, // .bind('fileuploadchunkalways', func); + + // The plugin options are used as settings object for the ajax calls. + // The following are jQuery ajax settings required for the file uploads: + processData: false, + contentType: false, + cache: false, + timeout: 0 + }, + + // A list of options that require reinitializing event listeners and/or + // special initialization code: + _specialOptions: [ + 'fileInput', + 'dropZone', + 'pasteZone', + 'multipart', + 'forceIframeTransport' + ], + + _blobSlice: + $.support.blobSlice && + function () { + var slice = this.slice || this.webkitSlice || this.mozSlice; + return slice.apply(this, arguments); + }, + + _BitrateTimer: function () { + this.timestamp = Date.now ? Date.now() : new Date().getTime(); + this.loaded = 0; + this.bitrate = 0; + this.getBitrate = function (now, loaded, interval) { + var timeDiff = now - this.timestamp; + if (!this.bitrate || !interval || timeDiff > interval) { + this.bitrate = (loaded - this.loaded) * (1000 / timeDiff) * 8; + this.loaded = loaded; + this.timestamp = now; + } + return this.bitrate; + }; + }, + + _isXHRUpload: function (options) { + return ( + !options.forceIframeTransport && + ((!options.multipart && $.support.xhrFileUpload) || + $.support.xhrFormDataFileUpload) + ); + }, + + _getFormData: function (options) { + var formData; + if ($.type(options.formData) === 'function') { + return options.formData(options.form); + } + if ($.isArray(options.formData)) { + return options.formData; + } + if ($.type(options.formData) === 'object') { + formData = []; + $.each(options.formData, function (name, value) { + formData.push({ name: name, value: value }); + }); + return formData; + } + return []; + }, + + _getTotal: function (files) { + var total = 0; + $.each(files, function (index, file) { + total += file.size || 1; + }); + return total; + }, + + _initProgressObject: function (obj) { + var progress = { + loaded: 0, + total: 0, + bitrate: 0 + }; + if (obj._progress) { + $.extend(obj._progress, progress); + } else { + obj._progress = progress; + } + }, + + _initResponseObject: function (obj) { + var prop; + if (obj._response) { + for (prop in obj._response) { + if (Object.prototype.hasOwnProperty.call(obj._response, prop)) { + delete obj._response[prop]; + } + } + } else { + obj._response = {}; + } + }, + + _onProgress: function (e, data) { + if (e.lengthComputable) { + var now = Date.now ? Date.now() : new Date().getTime(), + loaded; + if ( + data._time && + data.progressInterval && + now - data._time < data.progressInterval && + e.loaded !== e.total + ) { + return; + } + data._time = now; + loaded = + Math.floor( + (e.loaded / e.total) * (data.chunkSize || data._progress.total) + ) + (data.uploadedBytes || 0); + // Add the difference from the previously loaded state + // to the global loaded counter: + this._progress.loaded += loaded - data._progress.loaded; + this._progress.bitrate = this._bitrateTimer.getBitrate( + now, + this._progress.loaded, + data.bitrateInterval + ); + data._progress.loaded = data.loaded = loaded; + data._progress.bitrate = data.bitrate = data._bitrateTimer.getBitrate( + now, + loaded, + data.bitrateInterval + ); + // Trigger a custom progress event with a total data property set + // to the file size(s) of the current upload and a loaded data + // property calculated accordingly: + this._trigger( + 'progress', + $.Event('progress', { delegatedEvent: e }), + data + ); + // Trigger a global progress event for all current file uploads, + // including ajax calls queued for sequential file uploads: + this._trigger( + 'progressall', + $.Event('progressall', { delegatedEvent: e }), + this._progress + ); + } + }, + + _initProgressListener: function (options) { + var that = this, + xhr = options.xhr ? options.xhr() : $.ajaxSettings.xhr(); + // Accesss to the native XHR object is required to add event listeners + // for the upload progress event: + if (xhr.upload) { + $(xhr.upload).bind('progress', function (e) { + var oe = e.originalEvent; + // Make sure the progress event properties get copied over: + e.lengthComputable = oe.lengthComputable; + e.loaded = oe.loaded; + e.total = oe.total; + that._onProgress(e, options); + }); + options.xhr = function () { + return xhr; + }; + } + }, + + _deinitProgressListener: function (options) { + var xhr = options.xhr ? options.xhr() : $.ajaxSettings.xhr(); + if (xhr.upload) { + $(xhr.upload).unbind('progress'); + } + }, + + _isInstanceOf: function (type, obj) { + // Cross-frame instanceof check + return Object.prototype.toString.call(obj) === '[object ' + type + ']'; + }, + + _getUniqueFilename: function (name, map) { + // eslint-disable-next-line no-param-reassign + name = String(name); + if (map[name]) { + // eslint-disable-next-line no-param-reassign + name = name.replace(/(?: \(([\d]+)\))?(\.[^.]+)?$/, function ( + _, + p1, + p2 + ) { + var index = p1 ? Number(p1) + 1 : 1; + var ext = p2 || ''; + return ' (' + index + ')' + ext; + }); + return this._getUniqueFilename(name, map); + } + map[name] = true; + return name; + }, + + _initXHRData: function (options) { + var that = this, + formData, + file = options.files[0], + // Ignore non-multipart setting if not supported: + multipart = options.multipart || !$.support.xhrFileUpload, + paramName = + $.type(options.paramName) === 'array' + ? options.paramName[0] + : options.paramName; + options.headers = $.extend({}, options.headers); + if (options.contentRange) { + options.headers['Content-Range'] = options.contentRange; + } + if (!multipart || options.blob || !this._isInstanceOf('File', file)) { + options.headers['Content-Disposition'] = + 'attachment; filename="' + + encodeURI(file.uploadName || file.name) + + '"'; + } + if (!multipart) { + options.contentType = file.type || 'application/octet-stream'; + options.data = options.blob || file; + } else if ($.support.xhrFormDataFileUpload) { + if (options.postMessage) { + // window.postMessage does not allow sending FormData + // objects, so we just add the File/Blob objects to + // the formData array and let the postMessage window + // create the FormData object out of this array: + formData = this._getFormData(options); + if (options.blob) { + formData.push({ + name: paramName, + value: options.blob + }); + } else { + $.each(options.files, function (index, file) { + formData.push({ + name: + ($.type(options.paramName) === 'array' && + options.paramName[index]) || + paramName, + value: file + }); + }); + } + } else { + if (that._isInstanceOf('FormData', options.formData)) { + formData = options.formData; + } else { + formData = new FormData(); + $.each(this._getFormData(options), function (index, field) { + formData.append(field.name, field.value); + }); + } + if (options.blob) { + formData.append( + paramName, + options.blob, + file.uploadName || file.name + ); + } else { + $.each(options.files, function (index, file) { + // This check allows the tests to run with + // dummy objects: + if ( + that._isInstanceOf('File', file) || + that._isInstanceOf('Blob', file) + ) { + var fileName = file.uploadName || file.name; + if (options.uniqueFilenames) { + fileName = that._getUniqueFilename( + fileName, + options.uniqueFilenames + ); + } + formData.append( + ($.type(options.paramName) === 'array' && + options.paramName[index]) || + paramName, + file, + fileName + ); + } + }); + } + } + options.data = formData; + } + // Blob reference is not needed anymore, free memory: + options.blob = null; + }, + + _initIframeSettings: function (options) { + var targetHost = $('
      ') + .prop('href', options.url) + .prop('host'); + // Setting the dataType to iframe enables the iframe transport: + options.dataType = 'iframe ' + (options.dataType || ''); + // The iframe transport accepts a serialized array as form data: + options.formData = this._getFormData(options); + // Add redirect url to form data on cross-domain uploads: + if (options.redirect && targetHost && targetHost !== location.host) { + options.formData.push({ + name: options.redirectParamName || 'redirect', + value: options.redirect + }); + } + }, + + _initDataSettings: function (options) { + if (this._isXHRUpload(options)) { + if (!this._chunkedUpload(options, true)) { + if (!options.data) { + this._initXHRData(options); + } + this._initProgressListener(options); + } + if (options.postMessage) { + // Setting the dataType to postmessage enables the + // postMessage transport: + options.dataType = 'postmessage ' + (options.dataType || ''); + } + } else { + this._initIframeSettings(options); + } + }, + + _getParamName: function (options) { + var fileInput = $(options.fileInput), + paramName = options.paramName; + if (!paramName) { + paramName = []; + fileInput.each(function () { + var input = $(this), + name = input.prop('name') || 'files[]', + i = (input.prop('files') || [1]).length; + while (i) { + paramName.push(name); + i -= 1; + } + }); + if (!paramName.length) { + paramName = [fileInput.prop('name') || 'files[]']; + } + } else if (!$.isArray(paramName)) { + paramName = [paramName]; + } + return paramName; + }, + + _initFormSettings: function (options) { + // Retrieve missing options from the input field and the + // associated form, if available: + if (!options.form || !options.form.length) { + options.form = $(options.fileInput.prop('form')); + // If the given file input doesn't have an associated form, + // use the default widget file input's form: + if (!options.form.length) { + options.form = $(this.options.fileInput.prop('form')); + } + } + options.paramName = this._getParamName(options); + if (!options.url) { + options.url = options.form.prop('action') || location.href; + } + // The HTTP request method must be "POST" or "PUT": + options.type = ( + options.type || + ($.type(options.form.prop('method')) === 'string' && + options.form.prop('method')) || + '' + ).toUpperCase(); + if ( + options.type !== 'POST' && + options.type !== 'PUT' && + options.type !== 'PATCH' + ) { + options.type = 'POST'; + } + if (!options.formAcceptCharset) { + options.formAcceptCharset = options.form.attr('accept-charset'); + } + }, + + _getAJAXSettings: function (data) { + var options = $.extend({}, this.options, data); + this._initFormSettings(options); + this._initDataSettings(options); + return options; + }, + + // jQuery 1.6 doesn't provide .state(), + // while jQuery 1.8+ removed .isRejected() and .isResolved(): + _getDeferredState: function (deferred) { + if (deferred.state) { + return deferred.state(); + } + if (deferred.isResolved()) { + return 'resolved'; + } + if (deferred.isRejected()) { + return 'rejected'; + } + return 'pending'; + }, + + // Maps jqXHR callbacks to the equivalent + // methods of the given Promise object: + _enhancePromise: function (promise) { + promise.success = promise.done; + promise.error = promise.fail; + promise.complete = promise.always; + return promise; + }, + + // Creates and returns a Promise object enhanced with + // the jqXHR methods abort, success, error and complete: + _getXHRPromise: function (resolveOrReject, context, args) { + var dfd = $.Deferred(), + promise = dfd.promise(); + // eslint-disable-next-line no-param-reassign + context = context || this.options.context || promise; + if (resolveOrReject === true) { + dfd.resolveWith(context, args); + } else if (resolveOrReject === false) { + dfd.rejectWith(context, args); + } + promise.abort = dfd.promise; + return this._enhancePromise(promise); + }, + + // Adds convenience methods to the data callback argument: + _addConvenienceMethods: function (e, data) { + var that = this, + getPromise = function (args) { + return $.Deferred() + .resolveWith(that, args) + .promise(); + }; + data.process = function (resolveFunc, rejectFunc) { + if (resolveFunc || rejectFunc) { + data._processQueue = this._processQueue = ( + this._processQueue || getPromise([this]) + ) + .then(function () { + if (data.errorThrown) { + return $.Deferred() + .rejectWith(that, [data]) + .promise(); + } + return getPromise(arguments); + }) + .then(resolveFunc, rejectFunc); + } + return this._processQueue || getPromise([this]); + }; + data.submit = function () { + if (this.state() !== 'pending') { + data.jqXHR = this.jqXHR = + that._trigger( + 'submit', + $.Event('submit', { delegatedEvent: e }), + this + ) !== false && that._onSend(e, this); + } + return this.jqXHR || that._getXHRPromise(); + }; + data.abort = function () { + if (this.jqXHR) { + return this.jqXHR.abort(); + } + this.errorThrown = 'abort'; + that._trigger('fail', null, this); + return that._getXHRPromise(false); + }; + data.state = function () { + if (this.jqXHR) { + return that._getDeferredState(this.jqXHR); + } + if (this._processQueue) { + return that._getDeferredState(this._processQueue); + } + }; + data.processing = function () { + return ( + !this.jqXHR && + this._processQueue && + that._getDeferredState(this._processQueue) === 'pending' + ); + }; + data.progress = function () { + return this._progress; + }; + data.response = function () { + return this._response; + }; + }, + + // Parses the Range header from the server response + // and returns the uploaded bytes: + _getUploadedBytes: function (jqXHR) { + var range = jqXHR.getResponseHeader('Range'), + parts = range && range.split('-'), + upperBytesPos = parts && parts.length > 1 && parseInt(parts[1], 10); + return upperBytesPos && upperBytesPos + 1; + }, + + // Uploads a file in multiple, sequential requests + // by splitting the file up in multiple blob chunks. + // If the second parameter is true, only tests if the file + // should be uploaded in chunks, but does not invoke any + // upload requests: + _chunkedUpload: function (options, testOnly) { + options.uploadedBytes = options.uploadedBytes || 0; + var that = this, + file = options.files[0], + fs = file.size, + ub = options.uploadedBytes, + mcs = options.maxChunkSize || fs, + slice = this._blobSlice, + dfd = $.Deferred(), + promise = dfd.promise(), + jqXHR, + upload; + if ( + !( + this._isXHRUpload(options) && + slice && + (ub || ($.type(mcs) === 'function' ? mcs(options) : mcs) < fs) + ) || + options.data + ) { + return false; + } + if (testOnly) { + return true; + } + if (ub >= fs) { + file.error = options.i18n('uploadedBytes'); + return this._getXHRPromise(false, options.context, [ + null, + 'error', + file.error + ]); + } + // The chunk upload method: + upload = function () { + // Clone the options object for each chunk upload: + var o = $.extend({}, options), + currentLoaded = o._progress.loaded; + o.blob = slice.call( + file, + ub, + ub + ($.type(mcs) === 'function' ? mcs(o) : mcs), + file.type + ); + // Store the current chunk size, as the blob itself + // will be dereferenced after data processing: + o.chunkSize = o.blob.size; + // Expose the chunk bytes position range: + o.contentRange = + 'bytes ' + ub + '-' + (ub + o.chunkSize - 1) + '/' + fs; + // Trigger chunkbeforesend to allow form data to be updated for this chunk + that._trigger('chunkbeforesend', null, o); + // Process the upload data (the blob and potential form data): + that._initXHRData(o); + // Add progress listeners for this chunk upload: + that._initProgressListener(o); + jqXHR = ( + (that._trigger('chunksend', null, o) !== false && $.ajax(o)) || + that._getXHRPromise(false, o.context) + ) + .done(function (result, textStatus, jqXHR) { + ub = that._getUploadedBytes(jqXHR) || ub + o.chunkSize; + // Create a progress event if no final progress event + // with loaded equaling total has been triggered + // for this chunk: + if (currentLoaded + o.chunkSize - o._progress.loaded) { + that._onProgress( + $.Event('progress', { + lengthComputable: true, + loaded: ub - o.uploadedBytes, + total: ub - o.uploadedBytes + }), + o + ); + } + options.uploadedBytes = o.uploadedBytes = ub; + o.result = result; + o.textStatus = textStatus; + o.jqXHR = jqXHR; + that._trigger('chunkdone', null, o); + that._trigger('chunkalways', null, o); + if (ub < fs) { + // File upload not yet complete, + // continue with the next chunk: + upload(); + } else { + dfd.resolveWith(o.context, [result, textStatus, jqXHR]); + } + }) + .fail(function (jqXHR, textStatus, errorThrown) { + o.jqXHR = jqXHR; + o.textStatus = textStatus; + o.errorThrown = errorThrown; + that._trigger('chunkfail', null, o); + that._trigger('chunkalways', null, o); + dfd.rejectWith(o.context, [jqXHR, textStatus, errorThrown]); + }) + .always(function () { + that._deinitProgressListener(o); + }); + }; + this._enhancePromise(promise); + promise.abort = function () { + return jqXHR.abort(); + }; + upload(); + return promise; + }, + + _beforeSend: function (e, data) { + if (this._active === 0) { + // the start callback is triggered when an upload starts + // and no other uploads are currently running, + // equivalent to the global ajaxStart event: + this._trigger('start'); + // Set timer for global bitrate progress calculation: + this._bitrateTimer = new this._BitrateTimer(); + // Reset the global progress values: + this._progress.loaded = this._progress.total = 0; + this._progress.bitrate = 0; + } + // Make sure the container objects for the .response() and + // .progress() methods on the data object are available + // and reset to their initial state: + this._initResponseObject(data); + this._initProgressObject(data); + data._progress.loaded = data.loaded = data.uploadedBytes || 0; + data._progress.total = data.total = this._getTotal(data.files) || 1; + data._progress.bitrate = data.bitrate = 0; + this._active += 1; + // Initialize the global progress values: + this._progress.loaded += data.loaded; + this._progress.total += data.total; + }, + + _onDone: function (result, textStatus, jqXHR, options) { + var total = options._progress.total, + response = options._response; + if (options._progress.loaded < total) { + // Create a progress event if no final progress event + // with loaded equaling total has been triggered: + this._onProgress( + $.Event('progress', { + lengthComputable: true, + loaded: total, + total: total + }), + options + ); + } + response.result = options.result = result; + response.textStatus = options.textStatus = textStatus; + response.jqXHR = options.jqXHR = jqXHR; + this._trigger('done', null, options); + }, + + _onFail: function (jqXHR, textStatus, errorThrown, options) { + var response = options._response; + if (options.recalculateProgress) { + // Remove the failed (error or abort) file upload from + // the global progress calculation: + this._progress.loaded -= options._progress.loaded; + this._progress.total -= options._progress.total; + } + response.jqXHR = options.jqXHR = jqXHR; + response.textStatus = options.textStatus = textStatus; + response.errorThrown = options.errorThrown = errorThrown; + this._trigger('fail', null, options); + }, + + _onAlways: function (jqXHRorResult, textStatus, jqXHRorError, options) { + // jqXHRorResult, textStatus and jqXHRorError are added to the + // options object via done and fail callbacks + this._trigger('always', null, options); + }, + + _onSend: function (e, data) { + if (!data.submit) { + this._addConvenienceMethods(e, data); + } + var that = this, + jqXHR, + aborted, + slot, + pipe, + options = that._getAJAXSettings(data), + send = function () { + that._sending += 1; + // Set timer for bitrate progress calculation: + options._bitrateTimer = new that._BitrateTimer(); + jqXHR = + jqXHR || + ( + ((aborted || + that._trigger( + 'send', + $.Event('send', { delegatedEvent: e }), + options + ) === false) && + that._getXHRPromise(false, options.context, aborted)) || + that._chunkedUpload(options) || + $.ajax(options) + ) + .done(function (result, textStatus, jqXHR) { + that._onDone(result, textStatus, jqXHR, options); + }) + .fail(function (jqXHR, textStatus, errorThrown) { + that._onFail(jqXHR, textStatus, errorThrown, options); + }) + .always(function (jqXHRorResult, textStatus, jqXHRorError) { + that._deinitProgressListener(options); + that._onAlways( + jqXHRorResult, + textStatus, + jqXHRorError, + options + ); + that._sending -= 1; + that._active -= 1; + if ( + options.limitConcurrentUploads && + options.limitConcurrentUploads > that._sending + ) { + // Start the next queued upload, + // that has not been aborted: + var nextSlot = that._slots.shift(); + while (nextSlot) { + if (that._getDeferredState(nextSlot) === 'pending') { + nextSlot.resolve(); + break; + } + nextSlot = that._slots.shift(); + } + } + if (that._active === 0) { + // The stop callback is triggered when all uploads have + // been completed, equivalent to the global ajaxStop event: + that._trigger('stop'); + } + }); + return jqXHR; + }; + this._beforeSend(e, options); + if ( + this.options.sequentialUploads || + (this.options.limitConcurrentUploads && + this.options.limitConcurrentUploads <= this._sending) + ) { + if (this.options.limitConcurrentUploads > 1) { + slot = $.Deferred(); + this._slots.push(slot); + pipe = slot.then(send); + } else { + this._sequence = this._sequence.then(send, send); + pipe = this._sequence; + } + // Return the piped Promise object, enhanced with an abort method, + // which is delegated to the jqXHR object of the current upload, + // and jqXHR callbacks mapped to the equivalent Promise methods: + pipe.abort = function () { + aborted = [undefined, 'abort', 'abort']; + if (!jqXHR) { + if (slot) { + slot.rejectWith(options.context, aborted); + } + return send(); + } + return jqXHR.abort(); + }; + return this._enhancePromise(pipe); + } + return send(); + }, + + _onAdd: function (e, data) { + var that = this, + result = true, + options = $.extend({}, this.options, data), + files = data.files, + filesLength = files.length, + limit = options.limitMultiFileUploads, + limitSize = options.limitMultiFileUploadSize, + overhead = options.limitMultiFileUploadSizeOverhead, + batchSize = 0, + paramName = this._getParamName(options), + paramNameSet, + paramNameSlice, + fileSet, + i, + j = 0; + if (!filesLength) { + return false; + } + if (limitSize && files[0].size === undefined) { + limitSize = undefined; + } + if ( + !(options.singleFileUploads || limit || limitSize) || + !this._isXHRUpload(options) + ) { + fileSet = [files]; + paramNameSet = [paramName]; + } else if (!(options.singleFileUploads || limitSize) && limit) { + fileSet = []; + paramNameSet = []; + for (i = 0; i < filesLength; i += limit) { + fileSet.push(files.slice(i, i + limit)); + paramNameSlice = paramName.slice(i, i + limit); + if (!paramNameSlice.length) { + paramNameSlice = paramName; + } + paramNameSet.push(paramNameSlice); + } + } else if (!options.singleFileUploads && limitSize) { + fileSet = []; + paramNameSet = []; + for (i = 0; i < filesLength; i = i + 1) { + batchSize += files[i].size + overhead; + if ( + i + 1 === filesLength || + batchSize + files[i + 1].size + overhead > limitSize || + (limit && i + 1 - j >= limit) + ) { + fileSet.push(files.slice(j, i + 1)); + paramNameSlice = paramName.slice(j, i + 1); + if (!paramNameSlice.length) { + paramNameSlice = paramName; + } + paramNameSet.push(paramNameSlice); + j = i + 1; + batchSize = 0; + } + } + } else { + paramNameSet = paramName; + } + data.originalFiles = files; + $.each(fileSet || files, function (index, element) { + var newData = $.extend({}, data); + newData.files = fileSet ? element : [element]; + newData.paramName = paramNameSet[index]; + that._initResponseObject(newData); + that._initProgressObject(newData); + that._addConvenienceMethods(e, newData); + result = that._trigger( + 'add', + $.Event('add', { delegatedEvent: e }), + newData + ); + return result; + }); + return result; + }, + + _replaceFileInput: function (data) { + var input = data.fileInput, + inputClone = input.clone(true), + restoreFocus = input.is(document.activeElement); + // Add a reference for the new cloned file input to the data argument: + data.fileInputClone = inputClone; + $('
      ') + .append(inputClone)[0] + .reset(); + // Detaching allows to insert the fileInput on another form + // without loosing the file input value: + input.after(inputClone).detach(); + // If the fileInput had focus before it was detached, + // restore focus to the inputClone. + if (restoreFocus) { + inputClone.focus(); + } + // Avoid memory leaks with the detached file input: + $.cleanData(input.unbind('remove')); + // Replace the original file input element in the fileInput + // elements set with the clone, which has been copied including + // event handlers: + this.options.fileInput = this.options.fileInput.map(function (i, el) { + if (el === input[0]) { + return inputClone[0]; + } + return el; + }); + // If the widget has been initialized on the file input itself, + // override this.element with the file input clone: + if (input[0] === this.element[0]) { + this.element = inputClone; + } + }, + + _handleFileTreeEntry: function (entry, path) { + var that = this, + dfd = $.Deferred(), + entries = [], + dirReader, + errorHandler = function (e) { + if (e && !e.entry) { + e.entry = entry; + } + // Since $.when returns immediately if one + // Deferred is rejected, we use resolve instead. + // This allows valid files and invalid items + // to be returned together in one set: + dfd.resolve([e]); + }, + successHandler = function (entries) { + that + ._handleFileTreeEntries(entries, path + entry.name + '/') + .done(function (files) { + dfd.resolve(files); + }) + .fail(errorHandler); + }, + readEntries = function () { + dirReader.readEntries(function (results) { + if (!results.length) { + successHandler(entries); + } else { + entries = entries.concat(results); + readEntries(); + } + }, errorHandler); + }; + // eslint-disable-next-line no-param-reassign + path = path || ''; + if (entry.isFile) { + if (entry._file) { + // Workaround for Chrome bug #149735 + entry._file.relativePath = path; + dfd.resolve(entry._file); + } else { + entry.file(function (file) { + file.relativePath = path; + dfd.resolve(file); + }, errorHandler); + } + } else if (entry.isDirectory) { + dirReader = entry.createReader(); + readEntries(); + } else { + // Return an empty list for file system items + // other than files or directories: + dfd.resolve([]); + } + return dfd.promise(); + }, + + _handleFileTreeEntries: function (entries, path) { + var that = this; + return $.when + .apply( + $, + $.map(entries, function (entry) { + return that._handleFileTreeEntry(entry, path); + }) + ) + .then(function () { + return Array.prototype.concat.apply([], arguments); + }); + }, + + _getDroppedFiles: function (dataTransfer) { + // eslint-disable-next-line no-param-reassign + dataTransfer = dataTransfer || {}; + var items = dataTransfer.items; + if ( + items && + items.length && + (items[0].webkitGetAsEntry || items[0].getAsEntry) + ) { + return this._handleFileTreeEntries( + $.map(items, function (item) { + var entry; + if (item.webkitGetAsEntry) { + entry = item.webkitGetAsEntry(); + if (entry) { + // Workaround for Chrome bug #149735: + entry._file = item.getAsFile(); + } + return entry; + } + return item.getAsEntry(); + }) + ); + } + return $.Deferred() + .resolve($.makeArray(dataTransfer.files)) + .promise(); + }, + + _getSingleFileInputFiles: function (fileInput) { + // eslint-disable-next-line no-param-reassign + fileInput = $(fileInput); + var entries = + fileInput.prop('webkitEntries') || fileInput.prop('entries'), + files, + value; + if (entries && entries.length) { + return this._handleFileTreeEntries(entries); + } + files = $.makeArray(fileInput.prop('files')); + if (!files.length) { + value = fileInput.prop('value'); + if (!value) { + return $.Deferred() + .resolve([]) + .promise(); + } + // If the files property is not available, the browser does not + // support the File API and we add a pseudo File object with + // the input value as name with path information removed: + files = [{ name: value.replace(/^.*\\/, '') }]; + } else if (files[0].name === undefined && files[0].fileName) { + // File normalization for Safari 4 and Firefox 3: + $.each(files, function (index, file) { + file.name = file.fileName; + file.size = file.fileSize; + }); + } + return $.Deferred() + .resolve(files) + .promise(); + }, + + _getFileInputFiles: function (fileInput) { + if (!(fileInput instanceof $) || fileInput.length === 1) { + return this._getSingleFileInputFiles(fileInput); + } + return $.when + .apply($, $.map(fileInput, this._getSingleFileInputFiles)) + .then(function () { + return Array.prototype.concat.apply([], arguments); + }); + }, + + _onChange: function (e) { + var that = this, + data = { + fileInput: $(e.target), + form: $(e.target.form) + }; + this._getFileInputFiles(data.fileInput).always(function (files) { + data.files = files; + if (that.options.replaceFileInput) { + that._replaceFileInput(data); + } + if ( + that._trigger( + 'change', + $.Event('change', { delegatedEvent: e }), + data + ) !== false + ) { + that._onAdd(e, data); + } + }); + }, + + _onPaste: function (e) { + var items = + e.originalEvent && + e.originalEvent.clipboardData && + e.originalEvent.clipboardData.items, + data = { files: [] }; + if (items && items.length) { + $.each(items, function (index, item) { + var file = item.getAsFile && item.getAsFile(); + if (file) { + data.files.push(file); + } + }); + if ( + this._trigger( + 'paste', + $.Event('paste', { delegatedEvent: e }), + data + ) !== false + ) { + this._onAdd(e, data); + } + } + }, + + _onDrop: function (e) { + e.dataTransfer = e.originalEvent && e.originalEvent.dataTransfer; + var that = this, + dataTransfer = e.dataTransfer, + data = {}; + if (dataTransfer && dataTransfer.files && dataTransfer.files.length) { + e.preventDefault(); + this._getDroppedFiles(dataTransfer).always(function (files) { + data.files = files; + if ( + that._trigger( + 'drop', + $.Event('drop', { delegatedEvent: e }), + data + ) !== false + ) { + that._onAdd(e, data); + } + }); + } + }, + + _onDragOver: getDragHandler('dragover'), + + _onDragEnter: getDragHandler('dragenter'), + + _onDragLeave: getDragHandler('dragleave'), + + _initEventHandlers: function () { + if (this._isXHRUpload(this.options)) { + this._on(this.options.dropZone, { + dragover: this._onDragOver, + drop: this._onDrop, + // event.preventDefault() on dragenter is required for IE10+: + dragenter: this._onDragEnter, + // dragleave is not required, but added for completeness: + dragleave: this._onDragLeave + }); + this._on(this.options.pasteZone, { + paste: this._onPaste + }); + } + if ($.support.fileInput) { + this._on(this.options.fileInput, { + change: this._onChange + }); + } + }, + + _destroyEventHandlers: function () { + this._off(this.options.dropZone, 'dragenter dragleave dragover drop'); + this._off(this.options.pasteZone, 'paste'); + this._off(this.options.fileInput, 'change'); + }, + + _destroy: function () { + this._destroyEventHandlers(); + }, + + _setOption: function (key, value) { + var reinit = $.inArray(key, this._specialOptions) !== -1; + if (reinit) { + this._destroyEventHandlers(); + } + this._super(key, value); + if (reinit) { + this._initSpecialOptions(); + this._initEventHandlers(); + } + }, + + _initSpecialOptions: function () { + var options = this.options; + if (options.fileInput === undefined) { + options.fileInput = this.element.is('input[type="file"]') + ? this.element + : this.element.find('input[type="file"]'); + } else if (!(options.fileInput instanceof $)) { + options.fileInput = $(options.fileInput); + } + if (!(options.dropZone instanceof $)) { + options.dropZone = $(options.dropZone); + } + if (!(options.pasteZone instanceof $)) { + options.pasteZone = $(options.pasteZone); + } + }, + + _getRegExp: function (str) { + var parts = str.split('/'), + modifiers = parts.pop(); + parts.shift(); + return new RegExp(parts.join('/'), modifiers); + }, + + _isRegExpOption: function (key, value) { + return ( + key !== 'url' && + $.type(value) === 'string' && + /^\/.*\/[igm]{0,3}$/.test(value) + ); + }, + + _initDataAttributes: function () { + var that = this, + options = this.options, + data = this.element.data(); + // Initialize options set via HTML5 data-attributes: + $.each(this.element[0].attributes, function (index, attr) { + var key = attr.name.toLowerCase(), + value; + if (/^data-/.test(key)) { + // Convert hyphen-ated key to camelCase: + key = key.slice(5).replace(/-[a-z]/g, function (str) { + return str.charAt(1).toUpperCase(); + }); + value = data[key]; + if (that._isRegExpOption(key, value)) { + value = that._getRegExp(value); + } + options[key] = value; + } + }); + }, + + _create: function () { + this._initDataAttributes(); + this._initSpecialOptions(); + this._slots = []; + this._sequence = this._getXHRPromise(true); + this._sending = this._active = 0; + this._initProgressObject(this); + this._initEventHandlers(); + }, + + // This method is exposed to the widget API and allows to query + // the number of active uploads: + active: function () { + return this._active; + }, + + // This method is exposed to the widget API and allows to query + // the widget upload progress. + // It returns an object with loaded, total and bitrate properties + // for the running uploads: + progress: function () { + return this._progress; + }, + + // This method is exposed to the widget API and allows adding files + // using the fileupload API. The data parameter accepts an object which + // must have a files property and can contain additional options: + // .fileupload('add', {files: filesList}); + add: function (data) { + var that = this; + if (!data || this.options.disabled) { + return; + } + if (data.fileInput && !data.files) { + this._getFileInputFiles(data.fileInput).always(function (files) { + data.files = files; + that._onAdd(null, data); + }); + } else { + data.files = $.makeArray(data.files); + this._onAdd(null, data); + } + }, + + // This method is exposed to the widget API and allows sending files + // using the fileupload API. The data parameter accepts an object which + // must have a files or fileInput property and can contain additional options: + // .fileupload('send', {files: filesList}); + // The method returns a Promise object for the file upload call. + send: function (data) { + if (data && !this.options.disabled) { + if (data.fileInput && !data.files) { + var that = this, + dfd = $.Deferred(), + promise = dfd.promise(), + jqXHR, + aborted; + promise.abort = function () { + aborted = true; + if (jqXHR) { + return jqXHR.abort(); + } + dfd.reject(null, 'abort', 'abort'); + return promise; + }; + this._getFileInputFiles(data.fileInput).always(function (files) { + if (aborted) { + return; + } + if (!files.length) { + dfd.reject(); + return; + } + data.files = files; + jqXHR = that._onSend(null, data); + jqXHR.then( + function (result, textStatus, jqXHR) { + dfd.resolve(result, textStatus, jqXHR); + }, + function (jqXHR, textStatus, errorThrown) { + dfd.reject(jqXHR, textStatus, errorThrown); + } + ); + }); + return this._enhancePromise(promise); + } + data.files = $.makeArray(data.files); + if (data.files.length) { + return this._onSend(null, data); + } + } + return this._getXHRPromise(false, data && data.context); + } + }); +}); diff --git a/DNN Platform/JavaScript Libraries/jQuery.Fileupload/releaseNotes.txt b/DNN Platform/JavaScript Libraries/jQuery.Fileupload/releaseNotes.txt new file mode 100644 index 00000000000..e69de29bb2d diff --git a/DNN Platform/JavaScript Libraries/jQuery.iframe-transport/LICENSE.txt b/DNN Platform/JavaScript Libraries/jQuery.iframe-transport/LICENSE.txt new file mode 100644 index 00000000000..5dd45bf6728 --- /dev/null +++ b/DNN Platform/JavaScript Libraries/jQuery.iframe-transport/LICENSE.txt @@ -0,0 +1,20 @@ +MIT License + +Copyright 2010 Sebastian Tschan, https://blueimp.net + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/DNN Platform/JavaScript Libraries/jQuery.iframe-transport/jQuery.iframe-transport.dnn b/DNN Platform/JavaScript Libraries/jQuery.iframe-transport/jQuery.iframe-transport.dnn new file mode 100644 index 00000000000..c4a00f72969 --- /dev/null +++ b/DNN Platform/JavaScript Libraries/jQuery.iframe-transport/jQuery.iframe-transport.dnn @@ -0,0 +1,36 @@ + + + + jQuery Iframe Transport Plugin + An AJAX transport for jQuery using an iframe, for browsers that do not support uploads via XHR2. + Icons\Sigma\Extensions_32x32_Standard.png + + .NET Foundation and Contributors + DNN Community + https://dnncommunity.org + info@dnncommunity.org + + + + true + + + + jQuery.iframe-transport + jquery.iframe-transport.js + jQuery.ajaxSettings.converters['iframe json'] + https://cdnjs.cloudflare.com/ajax/libs/blueimp-file-upload/10.7.0/js/jquery.iframe-transport.min.js + + + + + jQuery.iframe-transport + + jquery.iframe-transport.js + + + + + + + diff --git a/DNN Platform/JavaScript Libraries/jQuery.iframe-transport/jquery.iframe-transport.js b/DNN Platform/JavaScript Libraries/jQuery.iframe-transport/jquery.iframe-transport.js new file mode 100644 index 00000000000..058cad6a381 --- /dev/null +++ b/DNN Platform/JavaScript Libraries/jQuery.iframe-transport/jquery.iframe-transport.js @@ -0,0 +1,221 @@ +/* + * jQuery Iframe Transport Plugin + * https://github.com/blueimp/jQuery-File-Upload + * + * Copyright 2011, Sebastian Tschan + * https://blueimp.net + * + * Licensed under the MIT license: + * https://opensource.org/licenses/MIT + */ + +/* global define, require */ + +(function (factory) { + 'use strict'; + if (typeof define === 'function' && define.amd) { + // Register as an anonymous AMD module: + define(['jquery'], factory); + } else if (typeof exports === 'object') { + // Node/CommonJS: + factory(require('jquery')); + } else { + // Browser globals: + factory(window.jQuery); + } +})(function ($) { + 'use strict'; + + // Helper variable to create unique names for the transport iframes: + var counter = 0, + jsonAPI = $, + jsonParse = 'parseJSON'; + + if ('JSON' in window && 'parse' in JSON) { + jsonAPI = JSON; + jsonParse = 'parse'; + } + + // The iframe transport accepts four additional options: + // options.fileInput: a jQuery collection of file input fields + // options.paramName: the parameter name for the file form data, + // overrides the name property of the file input field(s), + // can be a string or an array of strings. + // options.formData: an array of objects with name and value properties, + // equivalent to the return data of .serializeArray(), e.g.: + // [{name: 'a', value: 1}, {name: 'b', value: 2}] + // options.initialIframeSrc: the URL of the initial iframe src, + // by default set to "javascript:false;" + $.ajaxTransport('iframe', function (options) { + if (options.async) { + // javascript:false as initial iframe src + // prevents warning popups on HTTPS in IE6: + // eslint-disable-next-line no-script-url + var initialIframeSrc = options.initialIframeSrc || 'javascript:false;', + form, + iframe, + addParamChar; + return { + send: function (_, completeCallback) { + form = $('
      '); + form.attr('accept-charset', options.formAcceptCharset); + addParamChar = /\?/.test(options.url) ? '&' : '?'; + // XDomainRequest only supports GET and POST: + if (options.type === 'DELETE') { + options.url = options.url + addParamChar + '_method=DELETE'; + options.type = 'POST'; + } else if (options.type === 'PUT') { + options.url = options.url + addParamChar + '_method=PUT'; + options.type = 'POST'; + } else if (options.type === 'PATCH') { + options.url = options.url + addParamChar + '_method=PATCH'; + options.type = 'POST'; + } + // IE versions below IE8 cannot set the name property of + // elements that have already been added to the DOM, + // so we set the name along with the iframe HTML markup: + counter += 1; + iframe = $( + '' + ).bind('load', function () { + var fileInputClones, + paramNames = $.isArray(options.paramName) + ? options.paramName + : [options.paramName]; + iframe.unbind('load').bind('load', function () { + var response; + // Wrap in a try/catch block to catch exceptions thrown + // when trying to access cross-domain iframe contents: + try { + response = iframe.contents(); + // Google Chrome and Firefox do not throw an + // exception when calling iframe.contents() on + // cross-domain requests, so we unify the response: + if (!response.length || !response[0].firstChild) { + throw new Error(); + } + } catch (e) { + response = undefined; + } + // The complete callback returns the + // iframe content document as response object: + completeCallback(200, 'success', { iframe: response }); + // Fix for IE endless progress bar activity bug + // (happens on form submits to iframe targets): + $('').appendTo( + form + ); + window.setTimeout(function () { + // Removing the form in a setTimeout call + // allows Chrome's developer tools to display + // the response result + form.remove(); + }, 0); + }); + form + .prop('target', iframe.prop('name')) + .prop('action', options.url) + .prop('method', options.type); + if (options.formData) { + $.each(options.formData, function (index, field) { + $('') + .prop('name', field.name) + .val(field.value) + .appendTo(form); + }); + } + if ( + options.fileInput && + options.fileInput.length && + options.type === 'POST' + ) { + fileInputClones = options.fileInput.clone(); + // Insert a clone for each file input field: + options.fileInput.after(function (index) { + return fileInputClones[index]; + }); + if (options.paramName) { + options.fileInput.each(function (index) { + $(this).prop('name', paramNames[index] || options.paramName); + }); + } + // Appending the file input fields to the hidden form + // removes them from their original location: + form + .append(options.fileInput) + .prop('enctype', 'multipart/form-data') + // enctype must be set as encoding for IE: + .prop('encoding', 'multipart/form-data'); + // Remove the HTML5 form attribute from the input(s): + options.fileInput.removeAttr('form'); + } + form.submit(); + // Insert the file input fields at their original location + // by replacing the clones with the originals: + if (fileInputClones && fileInputClones.length) { + options.fileInput.each(function (index, input) { + var clone = $(fileInputClones[index]); + // Restore the original name and form properties: + $(input) + .prop('name', clone.prop('name')) + .attr('form', clone.attr('form')); + clone.replaceWith(input); + }); + } + }); + form.append(iframe).appendTo(document.body); + }, + abort: function () { + if (iframe) { + // javascript:false as iframe src aborts the request + // and prevents warning popups on HTTPS in IE6. + iframe.unbind('load').prop('src', initialIframeSrc); + } + if (form) { + form.remove(); + } + } + }; + } + }); + + // The iframe transport returns the iframe content document as response. + // The following adds converters from iframe to text, json, html, xml + // and script. + // Please note that the Content-Type for JSON responses has to be text/plain + // or text/html, if the browser doesn't include application/json in the + // Accept header, else IE will show a download dialog. + // The Content-Type for XML responses on the other hand has to be always + // application/xml or text/xml, so IE properly parses the XML response. + // See also + // https://github.com/blueimp/jQuery-File-Upload/wiki/Setup#content-type-negotiation + $.ajaxSetup({ + converters: { + 'iframe text': function (iframe) { + return iframe && $(iframe[0].body).text(); + }, + 'iframe json': function (iframe) { + return iframe && jsonAPI[jsonParse]($(iframe[0].body).text()); + }, + 'iframe html': function (iframe) { + return iframe && $(iframe[0].body).html(); + }, + 'iframe xml': function (iframe) { + var xmlDoc = iframe && iframe[0]; + return xmlDoc && $.isXMLDoc(xmlDoc) + ? xmlDoc + : $.parseXML( + (xmlDoc.XMLDocument && xmlDoc.XMLDocument.xml) || + $(xmlDoc.body).html() + ); + }, + 'iframe script': function (iframe) { + return iframe && $.globalEval($(iframe[0].body).text()); + } + } + }); +}); diff --git a/DNN Platform/JavaScript Libraries/jQuery.iframe-transport/releaseNotes.txt b/DNN Platform/JavaScript Libraries/jQuery.iframe-transport/releaseNotes.txt new file mode 100644 index 00000000000..e69de29bb2d diff --git a/DNN Platform/JavaScript Libraries/jQuery/jQuery.dnn b/DNN Platform/JavaScript Libraries/jQuery/jQuery.dnn index f92f63afebb..8045b32fd75 100644 --- a/DNN Platform/JavaScript Libraries/jQuery/jQuery.dnn +++ b/DNN Platform/JavaScript Libraries/jQuery/jQuery.dnn @@ -1,6 +1,6 @@ - + jQuery JavaScript Library jQuery is a JavaScript library that is used to manipulate the Document Object Model (DOM). Icons\Sigma\Extensions_32x32_Standard.png @@ -19,7 +19,7 @@ jQuery jquery.js jQuery - https://code.jquery.com/jquery-3.5.1.min.js + https://code.jquery.com/jquery-3.7.1.min.js diff --git a/DNN Platform/JavaScript Libraries/jQuery/jquery.js b/DNN Platform/JavaScript Libraries/jQuery/jquery.js index b0614034ad3..7f37b5d9912 100644 --- a/DNN Platform/JavaScript Libraries/jQuery/jquery.js +++ b/DNN Platform/JavaScript Libraries/jQuery/jquery.js @@ -1,2 +1,2 @@ -/*! jQuery v3.5.1 | (c) JS Foundation and other contributors | jquery.org/license */ -!function(e,t){"use strict";"object"==typeof module&&"object"==typeof module.exports?module.exports=e.document?t(e,!0):function(e){if(!e.document)throw new Error("jQuery requires a window with a document");return t(e)}:t(e)}("undefined"!=typeof window?window:this,function(C,e){"use strict";var t=[],r=Object.getPrototypeOf,s=t.slice,g=t.flat?function(e){return t.flat.call(e)}:function(e){return t.concat.apply([],e)},u=t.push,i=t.indexOf,n={},o=n.toString,v=n.hasOwnProperty,a=v.toString,l=a.call(Object),y={},m=function(e){return"function"==typeof e&&"number"!=typeof e.nodeType},x=function(e){return null!=e&&e===e.window},E=C.document,c={type:!0,src:!0,nonce:!0,noModule:!0};function b(e,t,n){var r,i,o=(n=n||E).createElement("script");if(o.text=e,t)for(r in c)(i=t[r]||t.getAttribute&&t.getAttribute(r))&&o.setAttribute(r,i);n.head.appendChild(o).parentNode.removeChild(o)}function w(e){return null==e?e+"":"object"==typeof e||"function"==typeof e?n[o.call(e)]||"object":typeof e}var f="3.5.1",S=function(e,t){return new S.fn.init(e,t)};function p(e){var t=!!e&&"length"in e&&e.length,n=w(e);return!m(e)&&!x(e)&&("array"===n||0===t||"number"==typeof t&&0+~]|"+M+")"+M+"*"),U=new RegExp(M+"|>"),X=new RegExp(F),V=new RegExp("^"+I+"$"),G={ID:new RegExp("^#("+I+")"),CLASS:new RegExp("^\\.("+I+")"),TAG:new RegExp("^("+I+"|[*])"),ATTR:new RegExp("^"+W),PSEUDO:new RegExp("^"+F),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+M+"*(even|odd|(([+-]|)(\\d*)n|)"+M+"*(?:([+-]|)"+M+"*(\\d+)|))"+M+"*\\)|)","i"),bool:new RegExp("^(?:"+R+")$","i"),needsContext:new RegExp("^"+M+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+M+"*((?:-\\d)?\\d*)"+M+"*\\)|)(?=[^-]|$)","i")},Y=/HTML$/i,Q=/^(?:input|select|textarea|button)$/i,J=/^h\d$/i,K=/^[^{]+\{\s*\[native \w/,Z=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,ee=/[+~]/,te=new RegExp("\\\\[\\da-fA-F]{1,6}"+M+"?|\\\\([^\\r\\n\\f])","g"),ne=function(e,t){var n="0x"+e.slice(1)-65536;return t||(n<0?String.fromCharCode(n+65536):String.fromCharCode(n>>10|55296,1023&n|56320))},re=/([\0-\x1f\x7f]|^-?\d)|^-$|[^\0-\x1f\x7f-\uFFFF\w-]/g,ie=function(e,t){return t?"\0"===e?"\ufffd":e.slice(0,-1)+"\\"+e.charCodeAt(e.length-1).toString(16)+" ":"\\"+e},oe=function(){T()},ae=be(function(e){return!0===e.disabled&&"fieldset"===e.nodeName.toLowerCase()},{dir:"parentNode",next:"legend"});try{H.apply(t=O.call(p.childNodes),p.childNodes),t[p.childNodes.length].nodeType}catch(e){H={apply:t.length?function(e,t){L.apply(e,O.call(t))}:function(e,t){var n=e.length,r=0;while(e[n++]=t[r++]);e.length=n-1}}}function se(t,e,n,r){var i,o,a,s,u,l,c,f=e&&e.ownerDocument,p=e?e.nodeType:9;if(n=n||[],"string"!=typeof t||!t||1!==p&&9!==p&&11!==p)return n;if(!r&&(T(e),e=e||C,E)){if(11!==p&&(u=Z.exec(t)))if(i=u[1]){if(9===p){if(!(a=e.getElementById(i)))return n;if(a.id===i)return n.push(a),n}else if(f&&(a=f.getElementById(i))&&y(e,a)&&a.id===i)return n.push(a),n}else{if(u[2])return H.apply(n,e.getElementsByTagName(t)),n;if((i=u[3])&&d.getElementsByClassName&&e.getElementsByClassName)return H.apply(n,e.getElementsByClassName(i)),n}if(d.qsa&&!N[t+" "]&&(!v||!v.test(t))&&(1!==p||"object"!==e.nodeName.toLowerCase())){if(c=t,f=e,1===p&&(U.test(t)||z.test(t))){(f=ee.test(t)&&ye(e.parentNode)||e)===e&&d.scope||((s=e.getAttribute("id"))?s=s.replace(re,ie):e.setAttribute("id",s=S)),o=(l=h(t)).length;while(o--)l[o]=(s?"#"+s:":scope")+" "+xe(l[o]);c=l.join(",")}try{return H.apply(n,f.querySelectorAll(c)),n}catch(e){N(t,!0)}finally{s===S&&e.removeAttribute("id")}}}return g(t.replace($,"$1"),e,n,r)}function ue(){var r=[];return function e(t,n){return r.push(t+" ")>b.cacheLength&&delete e[r.shift()],e[t+" "]=n}}function le(e){return e[S]=!0,e}function ce(e){var t=C.createElement("fieldset");try{return!!e(t)}catch(e){return!1}finally{t.parentNode&&t.parentNode.removeChild(t),t=null}}function fe(e,t){var n=e.split("|"),r=n.length;while(r--)b.attrHandle[n[r]]=t}function pe(e,t){var n=t&&e,r=n&&1===e.nodeType&&1===t.nodeType&&e.sourceIndex-t.sourceIndex;if(r)return r;if(n)while(n=n.nextSibling)if(n===t)return-1;return e?1:-1}function de(t){return function(e){return"input"===e.nodeName.toLowerCase()&&e.type===t}}function he(n){return function(e){var t=e.nodeName.toLowerCase();return("input"===t||"button"===t)&&e.type===n}}function ge(t){return function(e){return"form"in e?e.parentNode&&!1===e.disabled?"label"in e?"label"in e.parentNode?e.parentNode.disabled===t:e.disabled===t:e.isDisabled===t||e.isDisabled!==!t&&ae(e)===t:e.disabled===t:"label"in e&&e.disabled===t}}function ve(a){return le(function(o){return o=+o,le(function(e,t){var n,r=a([],e.length,o),i=r.length;while(i--)e[n=r[i]]&&(e[n]=!(t[n]=e[n]))})})}function ye(e){return e&&"undefined"!=typeof e.getElementsByTagName&&e}for(e in d=se.support={},i=se.isXML=function(e){var t=e.namespaceURI,n=(e.ownerDocument||e).documentElement;return!Y.test(t||n&&n.nodeName||"HTML")},T=se.setDocument=function(e){var t,n,r=e?e.ownerDocument||e:p;return r!=C&&9===r.nodeType&&r.documentElement&&(a=(C=r).documentElement,E=!i(C),p!=C&&(n=C.defaultView)&&n.top!==n&&(n.addEventListener?n.addEventListener("unload",oe,!1):n.attachEvent&&n.attachEvent("onunload",oe)),d.scope=ce(function(e){return a.appendChild(e).appendChild(C.createElement("div")),"undefined"!=typeof e.querySelectorAll&&!e.querySelectorAll(":scope fieldset div").length}),d.attributes=ce(function(e){return e.className="i",!e.getAttribute("className")}),d.getElementsByTagName=ce(function(e){return e.appendChild(C.createComment("")),!e.getElementsByTagName("*").length}),d.getElementsByClassName=K.test(C.getElementsByClassName),d.getById=ce(function(e){return a.appendChild(e).id=S,!C.getElementsByName||!C.getElementsByName(S).length}),d.getById?(b.filter.ID=function(e){var t=e.replace(te,ne);return function(e){return e.getAttribute("id")===t}},b.find.ID=function(e,t){if("undefined"!=typeof t.getElementById&&E){var n=t.getElementById(e);return n?[n]:[]}}):(b.filter.ID=function(e){var n=e.replace(te,ne);return function(e){var t="undefined"!=typeof e.getAttributeNode&&e.getAttributeNode("id");return t&&t.value===n}},b.find.ID=function(e,t){if("undefined"!=typeof t.getElementById&&E){var n,r,i,o=t.getElementById(e);if(o){if((n=o.getAttributeNode("id"))&&n.value===e)return[o];i=t.getElementsByName(e),r=0;while(o=i[r++])if((n=o.getAttributeNode("id"))&&n.value===e)return[o]}return[]}}),b.find.TAG=d.getElementsByTagName?function(e,t){return"undefined"!=typeof t.getElementsByTagName?t.getElementsByTagName(e):d.qsa?t.querySelectorAll(e):void 0}:function(e,t){var n,r=[],i=0,o=t.getElementsByTagName(e);if("*"===e){while(n=o[i++])1===n.nodeType&&r.push(n);return r}return o},b.find.CLASS=d.getElementsByClassName&&function(e,t){if("undefined"!=typeof t.getElementsByClassName&&E)return t.getElementsByClassName(e)},s=[],v=[],(d.qsa=K.test(C.querySelectorAll))&&(ce(function(e){var t;a.appendChild(e).innerHTML="",e.querySelectorAll("[msallowcapture^='']").length&&v.push("[*^$]="+M+"*(?:''|\"\")"),e.querySelectorAll("[selected]").length||v.push("\\["+M+"*(?:value|"+R+")"),e.querySelectorAll("[id~="+S+"-]").length||v.push("~="),(t=C.createElement("input")).setAttribute("name",""),e.appendChild(t),e.querySelectorAll("[name='']").length||v.push("\\["+M+"*name"+M+"*="+M+"*(?:''|\"\")"),e.querySelectorAll(":checked").length||v.push(":checked"),e.querySelectorAll("a#"+S+"+*").length||v.push(".#.+[+~]"),e.querySelectorAll("\\\f"),v.push("[\\r\\n\\f]")}),ce(function(e){e.innerHTML="
      ";var t=C.createElement("input");t.setAttribute("type","hidden"),e.appendChild(t).setAttribute("name","D"),e.querySelectorAll("[name=d]").length&&v.push("name"+M+"*[*^$|!~]?="),2!==e.querySelectorAll(":enabled").length&&v.push(":enabled",":disabled"),a.appendChild(e).disabled=!0,2!==e.querySelectorAll(":disabled").length&&v.push(":enabled",":disabled"),e.querySelectorAll("*,:x"),v.push(",.*:")})),(d.matchesSelector=K.test(c=a.matches||a.webkitMatchesSelector||a.mozMatchesSelector||a.oMatchesSelector||a.msMatchesSelector))&&ce(function(e){d.disconnectedMatch=c.call(e,"*"),c.call(e,"[s!='']:x"),s.push("!=",F)}),v=v.length&&new RegExp(v.join("|")),s=s.length&&new RegExp(s.join("|")),t=K.test(a.compareDocumentPosition),y=t||K.test(a.contains)?function(e,t){var n=9===e.nodeType?e.documentElement:e,r=t&&t.parentNode;return e===r||!(!r||1!==r.nodeType||!(n.contains?n.contains(r):e.compareDocumentPosition&&16&e.compareDocumentPosition(r)))}:function(e,t){if(t)while(t=t.parentNode)if(t===e)return!0;return!1},D=t?function(e,t){if(e===t)return l=!0,0;var n=!e.compareDocumentPosition-!t.compareDocumentPosition;return n||(1&(n=(e.ownerDocument||e)==(t.ownerDocument||t)?e.compareDocumentPosition(t):1)||!d.sortDetached&&t.compareDocumentPosition(e)===n?e==C||e.ownerDocument==p&&y(p,e)?-1:t==C||t.ownerDocument==p&&y(p,t)?1:u?P(u,e)-P(u,t):0:4&n?-1:1)}:function(e,t){if(e===t)return l=!0,0;var n,r=0,i=e.parentNode,o=t.parentNode,a=[e],s=[t];if(!i||!o)return e==C?-1:t==C?1:i?-1:o?1:u?P(u,e)-P(u,t):0;if(i===o)return pe(e,t);n=e;while(n=n.parentNode)a.unshift(n);n=t;while(n=n.parentNode)s.unshift(n);while(a[r]===s[r])r++;return r?pe(a[r],s[r]):a[r]==p?-1:s[r]==p?1:0}),C},se.matches=function(e,t){return se(e,null,null,t)},se.matchesSelector=function(e,t){if(T(e),d.matchesSelector&&E&&!N[t+" "]&&(!s||!s.test(t))&&(!v||!v.test(t)))try{var n=c.call(e,t);if(n||d.disconnectedMatch||e.document&&11!==e.document.nodeType)return n}catch(e){N(t,!0)}return 0":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(e){return e[1]=e[1].replace(te,ne),e[3]=(e[3]||e[4]||e[5]||"").replace(te,ne),"~="===e[2]&&(e[3]=" "+e[3]+" "),e.slice(0,4)},CHILD:function(e){return e[1]=e[1].toLowerCase(),"nth"===e[1].slice(0,3)?(e[3]||se.error(e[0]),e[4]=+(e[4]?e[5]+(e[6]||1):2*("even"===e[3]||"odd"===e[3])),e[5]=+(e[7]+e[8]||"odd"===e[3])):e[3]&&se.error(e[0]),e},PSEUDO:function(e){var t,n=!e[6]&&e[2];return G.CHILD.test(e[0])?null:(e[3]?e[2]=e[4]||e[5]||"":n&&X.test(n)&&(t=h(n,!0))&&(t=n.indexOf(")",n.length-t)-n.length)&&(e[0]=e[0].slice(0,t),e[2]=n.slice(0,t)),e.slice(0,3))}},filter:{TAG:function(e){var t=e.replace(te,ne).toLowerCase();return"*"===e?function(){return!0}:function(e){return e.nodeName&&e.nodeName.toLowerCase()===t}},CLASS:function(e){var t=m[e+" "];return t||(t=new RegExp("(^|"+M+")"+e+"("+M+"|$)"))&&m(e,function(e){return t.test("string"==typeof e.className&&e.className||"undefined"!=typeof e.getAttribute&&e.getAttribute("class")||"")})},ATTR:function(n,r,i){return function(e){var t=se.attr(e,n);return null==t?"!="===r:!r||(t+="","="===r?t===i:"!="===r?t!==i:"^="===r?i&&0===t.indexOf(i):"*="===r?i&&-1:\x20\t\r\n\f]*)[\x20\t\r\n\f]*\/?>(?:<\/\1>|)$/i;function D(e,n,r){return m(n)?S.grep(e,function(e,t){return!!n.call(e,t,e)!==r}):n.nodeType?S.grep(e,function(e){return e===n!==r}):"string"!=typeof n?S.grep(e,function(e){return-1)[^>]*|#([\w-]+))$/;(S.fn.init=function(e,t,n){var r,i;if(!e)return this;if(n=n||j,"string"==typeof e){if(!(r="<"===e[0]&&">"===e[e.length-1]&&3<=e.length?[null,e,null]:q.exec(e))||!r[1]&&t)return!t||t.jquery?(t||n).find(e):this.constructor(t).find(e);if(r[1]){if(t=t instanceof S?t[0]:t,S.merge(this,S.parseHTML(r[1],t&&t.nodeType?t.ownerDocument||t:E,!0)),N.test(r[1])&&S.isPlainObject(t))for(r in t)m(this[r])?this[r](t[r]):this.attr(r,t[r]);return this}return(i=E.getElementById(r[2]))&&(this[0]=i,this.length=1),this}return e.nodeType?(this[0]=e,this.length=1,this):m(e)?void 0!==n.ready?n.ready(e):e(S):S.makeArray(e,this)}).prototype=S.fn,j=S(E);var L=/^(?:parents|prev(?:Until|All))/,H={children:!0,contents:!0,next:!0,prev:!0};function O(e,t){while((e=e[t])&&1!==e.nodeType);return e}S.fn.extend({has:function(e){var t=S(e,this),n=t.length;return this.filter(function(){for(var e=0;e\x20\t\r\n\f]*)/i,he=/^$|^module$|\/(?:java|ecma)script/i;ce=E.createDocumentFragment().appendChild(E.createElement("div")),(fe=E.createElement("input")).setAttribute("type","radio"),fe.setAttribute("checked","checked"),fe.setAttribute("name","t"),ce.appendChild(fe),y.checkClone=ce.cloneNode(!0).cloneNode(!0).lastChild.checked,ce.innerHTML="",y.noCloneChecked=!!ce.cloneNode(!0).lastChild.defaultValue,ce.innerHTML="",y.option=!!ce.lastChild;var ge={thead:[1,"","
      "],col:[2,"","
      "],tr:[2,"","
      "],td:[3,"","
      "],_default:[0,"",""]};function ve(e,t){var n;return n="undefined"!=typeof e.getElementsByTagName?e.getElementsByTagName(t||"*"):"undefined"!=typeof e.querySelectorAll?e.querySelectorAll(t||"*"):[],void 0===t||t&&A(e,t)?S.merge([e],n):n}function ye(e,t){for(var n=0,r=e.length;n",""]);var me=/<|&#?\w+;/;function xe(e,t,n,r,i){for(var o,a,s,u,l,c,f=t.createDocumentFragment(),p=[],d=0,h=e.length;d\s*$/g;function qe(e,t){return A(e,"table")&&A(11!==t.nodeType?t:t.firstChild,"tr")&&S(e).children("tbody")[0]||e}function Le(e){return e.type=(null!==e.getAttribute("type"))+"/"+e.type,e}function He(e){return"true/"===(e.type||"").slice(0,5)?e.type=e.type.slice(5):e.removeAttribute("type"),e}function Oe(e,t){var n,r,i,o,a,s;if(1===t.nodeType){if(Y.hasData(e)&&(s=Y.get(e).events))for(i in Y.remove(t,"handle events"),s)for(n=0,r=s[i].length;n").attr(n.scriptAttrs||{}).prop({charset:n.scriptCharset,src:n.url}).on("load error",i=function(e){r.remove(),i=null,e&&t("error"===e.type?404:200,e.type)}),E.head.appendChild(r[0])},abort:function(){i&&i()}}});var Ut,Xt=[],Vt=/(=)\?(?=&|$)|\?\?/;S.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var e=Xt.pop()||S.expando+"_"+Ct.guid++;return this[e]=!0,e}}),S.ajaxPrefilter("json jsonp",function(e,t,n){var r,i,o,a=!1!==e.jsonp&&(Vt.test(e.url)?"url":"string"==typeof e.data&&0===(e.contentType||"").indexOf("application/x-www-form-urlencoded")&&Vt.test(e.data)&&"data");if(a||"jsonp"===e.dataTypes[0])return r=e.jsonpCallback=m(e.jsonpCallback)?e.jsonpCallback():e.jsonpCallback,a?e[a]=e[a].replace(Vt,"$1"+r):!1!==e.jsonp&&(e.url+=(Et.test(e.url)?"&":"?")+e.jsonp+"="+r),e.converters["script json"]=function(){return o||S.error(r+" was not called"),o[0]},e.dataTypes[0]="json",i=C[r],C[r]=function(){o=arguments},n.always(function(){void 0===i?S(C).removeProp(r):C[r]=i,e[r]&&(e.jsonpCallback=t.jsonpCallback,Xt.push(r)),o&&m(i)&&i(o[0]),o=i=void 0}),"script"}),y.createHTMLDocument=((Ut=E.implementation.createHTMLDocument("").body).innerHTML="
      ",2===Ut.childNodes.length),S.parseHTML=function(e,t,n){return"string"!=typeof e?[]:("boolean"==typeof t&&(n=t,t=!1),t||(y.createHTMLDocument?((r=(t=E.implementation.createHTMLDocument("")).createElement("base")).href=E.location.href,t.head.appendChild(r)):t=E),o=!n&&[],(i=N.exec(e))?[t.createElement(i[1])]:(i=xe([e],t,o),o&&o.length&&S(o).remove(),S.merge([],i.childNodes)));var r,i,o},S.fn.load=function(e,t,n){var r,i,o,a=this,s=e.indexOf(" ");return-1").append(S.parseHTML(e)).find(r):e)}).always(n&&function(e,t){a.each(function(){n.apply(this,o||[e.responseText,t,e])})}),this},S.expr.pseudos.animated=function(t){return S.grep(S.timers,function(e){return t===e.elem}).length},S.offset={setOffset:function(e,t,n){var r,i,o,a,s,u,l=S.css(e,"position"),c=S(e),f={};"static"===l&&(e.style.position="relative"),s=c.offset(),o=S.css(e,"top"),u=S.css(e,"left"),("absolute"===l||"fixed"===l)&&-1<(o+u).indexOf("auto")?(a=(r=c.position()).top,i=r.left):(a=parseFloat(o)||0,i=parseFloat(u)||0),m(t)&&(t=t.call(e,n,S.extend({},s))),null!=t.top&&(f.top=t.top-s.top+a),null!=t.left&&(f.left=t.left-s.left+i),"using"in t?t.using.call(e,f):("number"==typeof f.top&&(f.top+="px"),"number"==typeof f.left&&(f.left+="px"),c.css(f))}},S.fn.extend({offset:function(t){if(arguments.length)return void 0===t?this:this.each(function(e){S.offset.setOffset(this,t,e)});var e,n,r=this[0];return r?r.getClientRects().length?(e=r.getBoundingClientRect(),n=r.ownerDocument.defaultView,{top:e.top+n.pageYOffset,left:e.left+n.pageXOffset}):{top:0,left:0}:void 0},position:function(){if(this[0]){var e,t,n,r=this[0],i={top:0,left:0};if("fixed"===S.css(r,"position"))t=r.getBoundingClientRect();else{t=this.offset(),n=r.ownerDocument,e=r.offsetParent||n.documentElement;while(e&&(e===n.body||e===n.documentElement)&&"static"===S.css(e,"position"))e=e.parentNode;e&&e!==r&&1===e.nodeType&&((i=S(e).offset()).top+=S.css(e,"borderTopWidth",!0),i.left+=S.css(e,"borderLeftWidth",!0))}return{top:t.top-i.top-S.css(r,"marginTop",!0),left:t.left-i.left-S.css(r,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){var e=this.offsetParent;while(e&&"static"===S.css(e,"position"))e=e.offsetParent;return e||re})}}),S.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(t,i){var o="pageYOffset"===i;S.fn[t]=function(e){return $(this,function(e,t,n){var r;if(x(e)?r=e:9===e.nodeType&&(r=e.defaultView),void 0===n)return r?r[i]:e[t];r?r.scrollTo(o?r.pageXOffset:n,o?n:r.pageYOffset):e[t]=n},t,e,arguments.length)}}),S.each(["top","left"],function(e,n){S.cssHooks[n]=$e(y.pixelPosition,function(e,t){if(t)return t=Be(e,n),Me.test(t)?S(e).position()[n]+"px":t})}),S.each({Height:"height",Width:"width"},function(a,s){S.each({padding:"inner"+a,content:s,"":"outer"+a},function(r,o){S.fn[o]=function(e,t){var n=arguments.length&&(r||"boolean"!=typeof e),i=r||(!0===e||!0===t?"margin":"border");return $(this,function(e,t,n){var r;return x(e)?0===o.indexOf("outer")?e["inner"+a]:e.document.documentElement["client"+a]:9===e.nodeType?(r=e.documentElement,Math.max(e.body["scroll"+a],r["scroll"+a],e.body["offset"+a],r["offset"+a],r["client"+a])):void 0===n?S.css(e,t,i):S.style(e,t,n,i)},s,n?e:void 0,n)}})}),S.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(e,t){S.fn[t]=function(e){return this.on(t,e)}}),S.fn.extend({bind:function(e,t,n){return this.on(e,null,t,n)},unbind:function(e,t){return this.off(e,null,t)},delegate:function(e,t,n,r){return this.on(t,e,n,r)},undelegate:function(e,t,n){return 1===arguments.length?this.off(e,"**"):this.off(t,e||"**",n)},hover:function(e,t){return this.mouseenter(e).mouseleave(t||e)}}),S.each("blur focus focusin focusout resize scroll click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup contextmenu".split(" "),function(e,n){S.fn[n]=function(e,t){return 0+~]|"+ge+")"+ge+"*"),x=new RegExp(ge+"|>"),j=new RegExp(g),A=new RegExp("^"+t+"$"),D={ID:new RegExp("^#("+t+")"),CLASS:new RegExp("^\\.("+t+")"),TAG:new RegExp("^("+t+"|[*])"),ATTR:new RegExp("^"+p),PSEUDO:new RegExp("^"+g),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+ge+"*(even|odd|(([+-]|)(\\d*)n|)"+ge+"*(?:([+-]|)"+ge+"*(\\d+)|))"+ge+"*\\)|)","i"),bool:new RegExp("^(?:"+f+")$","i"),needsContext:new RegExp("^"+ge+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+ge+"*((?:-\\d)?\\d*)"+ge+"*\\)|)(?=[^-]|$)","i")},N=/^(?:input|select|textarea|button)$/i,q=/^h\d$/i,L=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,H=/[+~]/,O=new RegExp("\\\\[\\da-fA-F]{1,6}"+ge+"?|\\\\([^\\r\\n\\f])","g"),P=function(e,t){var n="0x"+e.slice(1)-65536;return t||(n<0?String.fromCharCode(n+65536):String.fromCharCode(n>>10|55296,1023&n|56320))},M=function(){V()},R=J(function(e){return!0===e.disabled&&fe(e,"fieldset")},{dir:"parentNode",next:"legend"});try{k.apply(oe=ae.call(ye.childNodes),ye.childNodes),oe[ye.childNodes.length].nodeType}catch(e){k={apply:function(e,t){me.apply(e,ae.call(t))},call:function(e){me.apply(e,ae.call(arguments,1))}}}function I(t,e,n,r){var i,o,a,s,u,l,c,f=e&&e.ownerDocument,p=e?e.nodeType:9;if(n=n||[],"string"!=typeof t||!t||1!==p&&9!==p&&11!==p)return n;if(!r&&(V(e),e=e||T,C)){if(11!==p&&(u=L.exec(t)))if(i=u[1]){if(9===p){if(!(a=e.getElementById(i)))return n;if(a.id===i)return k.call(n,a),n}else if(f&&(a=f.getElementById(i))&&I.contains(e,a)&&a.id===i)return k.call(n,a),n}else{if(u[2])return k.apply(n,e.getElementsByTagName(t)),n;if((i=u[3])&&e.getElementsByClassName)return k.apply(n,e.getElementsByClassName(i)),n}if(!(h[t+" "]||d&&d.test(t))){if(c=t,f=e,1===p&&(x.test(t)||m.test(t))){(f=H.test(t)&&U(e.parentNode)||e)==e&&le.scope||((s=e.getAttribute("id"))?s=ce.escapeSelector(s):e.setAttribute("id",s=S)),o=(l=Y(t)).length;while(o--)l[o]=(s?"#"+s:":scope")+" "+Q(l[o]);c=l.join(",")}try{return k.apply(n,f.querySelectorAll(c)),n}catch(e){h(t,!0)}finally{s===S&&e.removeAttribute("id")}}}return re(t.replace(ve,"$1"),e,n,r)}function W(){var r=[];return function e(t,n){return r.push(t+" ")>b.cacheLength&&delete e[r.shift()],e[t+" "]=n}}function F(e){return e[S]=!0,e}function $(e){var t=T.createElement("fieldset");try{return!!e(t)}catch(e){return!1}finally{t.parentNode&&t.parentNode.removeChild(t),t=null}}function B(t){return function(e){return fe(e,"input")&&e.type===t}}function _(t){return function(e){return(fe(e,"input")||fe(e,"button"))&&e.type===t}}function z(t){return function(e){return"form"in e?e.parentNode&&!1===e.disabled?"label"in e?"label"in e.parentNode?e.parentNode.disabled===t:e.disabled===t:e.isDisabled===t||e.isDisabled!==!t&&R(e)===t:e.disabled===t:"label"in e&&e.disabled===t}}function X(a){return F(function(o){return o=+o,F(function(e,t){var n,r=a([],e.length,o),i=r.length;while(i--)e[n=r[i]]&&(e[n]=!(t[n]=e[n]))})})}function U(e){return e&&"undefined"!=typeof e.getElementsByTagName&&e}function V(e){var t,n=e?e.ownerDocument||e:ye;return n!=T&&9===n.nodeType&&n.documentElement&&(r=(T=n).documentElement,C=!ce.isXMLDoc(T),i=r.matches||r.webkitMatchesSelector||r.msMatchesSelector,r.msMatchesSelector&&ye!=T&&(t=T.defaultView)&&t.top!==t&&t.addEventListener("unload",M),le.getById=$(function(e){return r.appendChild(e).id=ce.expando,!T.getElementsByName||!T.getElementsByName(ce.expando).length}),le.disconnectedMatch=$(function(e){return i.call(e,"*")}),le.scope=$(function(){return T.querySelectorAll(":scope")}),le.cssHas=$(function(){try{return T.querySelector(":has(*,:jqfake)"),!1}catch(e){return!0}}),le.getById?(b.filter.ID=function(e){var t=e.replace(O,P);return function(e){return e.getAttribute("id")===t}},b.find.ID=function(e,t){if("undefined"!=typeof t.getElementById&&C){var n=t.getElementById(e);return n?[n]:[]}}):(b.filter.ID=function(e){var n=e.replace(O,P);return function(e){var t="undefined"!=typeof e.getAttributeNode&&e.getAttributeNode("id");return t&&t.value===n}},b.find.ID=function(e,t){if("undefined"!=typeof t.getElementById&&C){var n,r,i,o=t.getElementById(e);if(o){if((n=o.getAttributeNode("id"))&&n.value===e)return[o];i=t.getElementsByName(e),r=0;while(o=i[r++])if((n=o.getAttributeNode("id"))&&n.value===e)return[o]}return[]}}),b.find.TAG=function(e,t){return"undefined"!=typeof t.getElementsByTagName?t.getElementsByTagName(e):t.querySelectorAll(e)},b.find.CLASS=function(e,t){if("undefined"!=typeof t.getElementsByClassName&&C)return t.getElementsByClassName(e)},d=[],$(function(e){var t;r.appendChild(e).innerHTML="",e.querySelectorAll("[selected]").length||d.push("\\["+ge+"*(?:value|"+f+")"),e.querySelectorAll("[id~="+S+"-]").length||d.push("~="),e.querySelectorAll("a#"+S+"+*").length||d.push(".#.+[+~]"),e.querySelectorAll(":checked").length||d.push(":checked"),(t=T.createElement("input")).setAttribute("type","hidden"),e.appendChild(t).setAttribute("name","D"),r.appendChild(e).disabled=!0,2!==e.querySelectorAll(":disabled").length&&d.push(":enabled",":disabled"),(t=T.createElement("input")).setAttribute("name",""),e.appendChild(t),e.querySelectorAll("[name='']").length||d.push("\\["+ge+"*name"+ge+"*="+ge+"*(?:''|\"\")")}),le.cssHas||d.push(":has"),d=d.length&&new RegExp(d.join("|")),l=function(e,t){if(e===t)return a=!0,0;var n=!e.compareDocumentPosition-!t.compareDocumentPosition;return n||(1&(n=(e.ownerDocument||e)==(t.ownerDocument||t)?e.compareDocumentPosition(t):1)||!le.sortDetached&&t.compareDocumentPosition(e)===n?e===T||e.ownerDocument==ye&&I.contains(ye,e)?-1:t===T||t.ownerDocument==ye&&I.contains(ye,t)?1:o?se.call(o,e)-se.call(o,t):0:4&n?-1:1)}),T}for(e in I.matches=function(e,t){return I(e,null,null,t)},I.matchesSelector=function(e,t){if(V(e),C&&!h[t+" "]&&(!d||!d.test(t)))try{var n=i.call(e,t);if(n||le.disconnectedMatch||e.document&&11!==e.document.nodeType)return n}catch(e){h(t,!0)}return 0":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(e){return e[1]=e[1].replace(O,P),e[3]=(e[3]||e[4]||e[5]||"").replace(O,P),"~="===e[2]&&(e[3]=" "+e[3]+" "),e.slice(0,4)},CHILD:function(e){return e[1]=e[1].toLowerCase(),"nth"===e[1].slice(0,3)?(e[3]||I.error(e[0]),e[4]=+(e[4]?e[5]+(e[6]||1):2*("even"===e[3]||"odd"===e[3])),e[5]=+(e[7]+e[8]||"odd"===e[3])):e[3]&&I.error(e[0]),e},PSEUDO:function(e){var t,n=!e[6]&&e[2];return D.CHILD.test(e[0])?null:(e[3]?e[2]=e[4]||e[5]||"":n&&j.test(n)&&(t=Y(n,!0))&&(t=n.indexOf(")",n.length-t)-n.length)&&(e[0]=e[0].slice(0,t),e[2]=n.slice(0,t)),e.slice(0,3))}},filter:{TAG:function(e){var t=e.replace(O,P).toLowerCase();return"*"===e?function(){return!0}:function(e){return fe(e,t)}},CLASS:function(e){var t=s[e+" "];return t||(t=new RegExp("(^|"+ge+")"+e+"("+ge+"|$)"))&&s(e,function(e){return t.test("string"==typeof e.className&&e.className||"undefined"!=typeof e.getAttribute&&e.getAttribute("class")||"")})},ATTR:function(n,r,i){return function(e){var t=I.attr(e,n);return null==t?"!="===r:!r||(t+="","="===r?t===i:"!="===r?t!==i:"^="===r?i&&0===t.indexOf(i):"*="===r?i&&-1:\x20\t\r\n\f]*)[\x20\t\r\n\f]*\/?>(?:<\/\1>|)$/i;function T(e,n,r){return v(n)?ce.grep(e,function(e,t){return!!n.call(e,t,e)!==r}):n.nodeType?ce.grep(e,function(e){return e===n!==r}):"string"!=typeof n?ce.grep(e,function(e){return-1)[^>]*|#([\w-]+))$/;(ce.fn.init=function(e,t,n){var r,i;if(!e)return this;if(n=n||k,"string"==typeof e){if(!(r="<"===e[0]&&">"===e[e.length-1]&&3<=e.length?[null,e,null]:S.exec(e))||!r[1]&&t)return!t||t.jquery?(t||n).find(e):this.constructor(t).find(e);if(r[1]){if(t=t instanceof ce?t[0]:t,ce.merge(this,ce.parseHTML(r[1],t&&t.nodeType?t.ownerDocument||t:C,!0)),w.test(r[1])&&ce.isPlainObject(t))for(r in t)v(this[r])?this[r](t[r]):this.attr(r,t[r]);return this}return(i=C.getElementById(r[2]))&&(this[0]=i,this.length=1),this}return e.nodeType?(this[0]=e,this.length=1,this):v(e)?void 0!==n.ready?n.ready(e):e(ce):ce.makeArray(e,this)}).prototype=ce.fn,k=ce(C);var E=/^(?:parents|prev(?:Until|All))/,j={children:!0,contents:!0,next:!0,prev:!0};function A(e,t){while((e=e[t])&&1!==e.nodeType);return e}ce.fn.extend({has:function(e){var t=ce(e,this),n=t.length;return this.filter(function(){for(var e=0;e\x20\t\r\n\f]*)/i,Ce=/^$|^module$|\/(?:java|ecma)script/i;xe=C.createDocumentFragment().appendChild(C.createElement("div")),(be=C.createElement("input")).setAttribute("type","radio"),be.setAttribute("checked","checked"),be.setAttribute("name","t"),xe.appendChild(be),le.checkClone=xe.cloneNode(!0).cloneNode(!0).lastChild.checked,xe.innerHTML="",le.noCloneChecked=!!xe.cloneNode(!0).lastChild.defaultValue,xe.innerHTML="",le.option=!!xe.lastChild;var ke={thead:[1,"","
      "],col:[2,"","
      "],tr:[2,"","
      "],td:[3,"","
      "],_default:[0,"",""]};function Se(e,t){var n;return n="undefined"!=typeof e.getElementsByTagName?e.getElementsByTagName(t||"*"):"undefined"!=typeof e.querySelectorAll?e.querySelectorAll(t||"*"):[],void 0===t||t&&fe(e,t)?ce.merge([e],n):n}function Ee(e,t){for(var n=0,r=e.length;n",""]);var je=/<|&#?\w+;/;function Ae(e,t,n,r,i){for(var o,a,s,u,l,c,f=t.createDocumentFragment(),p=[],d=0,h=e.length;d\s*$/g;function Re(e,t){return fe(e,"table")&&fe(11!==t.nodeType?t:t.firstChild,"tr")&&ce(e).children("tbody")[0]||e}function Ie(e){return e.type=(null!==e.getAttribute("type"))+"/"+e.type,e}function We(e){return"true/"===(e.type||"").slice(0,5)?e.type=e.type.slice(5):e.removeAttribute("type"),e}function Fe(e,t){var n,r,i,o,a,s;if(1===t.nodeType){if(_.hasData(e)&&(s=_.get(e).events))for(i in _.remove(t,"handle events"),s)for(n=0,r=s[i].length;n").attr(n.scriptAttrs||{}).prop({charset:n.scriptCharset,src:n.url}).on("load error",i=function(e){r.remove(),i=null,e&&t("error"===e.type?404:200,e.type)}),C.head.appendChild(r[0])},abort:function(){i&&i()}}});var Jt,Kt=[],Zt=/(=)\?(?=&|$)|\?\?/;ce.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var e=Kt.pop()||ce.expando+"_"+jt.guid++;return this[e]=!0,e}}),ce.ajaxPrefilter("json jsonp",function(e,t,n){var r,i,o,a=!1!==e.jsonp&&(Zt.test(e.url)?"url":"string"==typeof e.data&&0===(e.contentType||"").indexOf("application/x-www-form-urlencoded")&&Zt.test(e.data)&&"data");if(a||"jsonp"===e.dataTypes[0])return r=e.jsonpCallback=v(e.jsonpCallback)?e.jsonpCallback():e.jsonpCallback,a?e[a]=e[a].replace(Zt,"$1"+r):!1!==e.jsonp&&(e.url+=(At.test(e.url)?"&":"?")+e.jsonp+"="+r),e.converters["script json"]=function(){return o||ce.error(r+" was not called"),o[0]},e.dataTypes[0]="json",i=ie[r],ie[r]=function(){o=arguments},n.always(function(){void 0===i?ce(ie).removeProp(r):ie[r]=i,e[r]&&(e.jsonpCallback=t.jsonpCallback,Kt.push(r)),o&&v(i)&&i(o[0]),o=i=void 0}),"script"}),le.createHTMLDocument=((Jt=C.implementation.createHTMLDocument("").body).innerHTML="
      ",2===Jt.childNodes.length),ce.parseHTML=function(e,t,n){return"string"!=typeof e?[]:("boolean"==typeof t&&(n=t,t=!1),t||(le.createHTMLDocument?((r=(t=C.implementation.createHTMLDocument("")).createElement("base")).href=C.location.href,t.head.appendChild(r)):t=C),o=!n&&[],(i=w.exec(e))?[t.createElement(i[1])]:(i=Ae([e],t,o),o&&o.length&&ce(o).remove(),ce.merge([],i.childNodes)));var r,i,o},ce.fn.load=function(e,t,n){var r,i,o,a=this,s=e.indexOf(" ");return-1").append(ce.parseHTML(e)).find(r):e)}).always(n&&function(e,t){a.each(function(){n.apply(this,o||[e.responseText,t,e])})}),this},ce.expr.pseudos.animated=function(t){return ce.grep(ce.timers,function(e){return t===e.elem}).length},ce.offset={setOffset:function(e,t,n){var r,i,o,a,s,u,l=ce.css(e,"position"),c=ce(e),f={};"static"===l&&(e.style.position="relative"),s=c.offset(),o=ce.css(e,"top"),u=ce.css(e,"left"),("absolute"===l||"fixed"===l)&&-1<(o+u).indexOf("auto")?(a=(r=c.position()).top,i=r.left):(a=parseFloat(o)||0,i=parseFloat(u)||0),v(t)&&(t=t.call(e,n,ce.extend({},s))),null!=t.top&&(f.top=t.top-s.top+a),null!=t.left&&(f.left=t.left-s.left+i),"using"in t?t.using.call(e,f):c.css(f)}},ce.fn.extend({offset:function(t){if(arguments.length)return void 0===t?this:this.each(function(e){ce.offset.setOffset(this,t,e)});var e,n,r=this[0];return r?r.getClientRects().length?(e=r.getBoundingClientRect(),n=r.ownerDocument.defaultView,{top:e.top+n.pageYOffset,left:e.left+n.pageXOffset}):{top:0,left:0}:void 0},position:function(){if(this[0]){var e,t,n,r=this[0],i={top:0,left:0};if("fixed"===ce.css(r,"position"))t=r.getBoundingClientRect();else{t=this.offset(),n=r.ownerDocument,e=r.offsetParent||n.documentElement;while(e&&(e===n.body||e===n.documentElement)&&"static"===ce.css(e,"position"))e=e.parentNode;e&&e!==r&&1===e.nodeType&&((i=ce(e).offset()).top+=ce.css(e,"borderTopWidth",!0),i.left+=ce.css(e,"borderLeftWidth",!0))}return{top:t.top-i.top-ce.css(r,"marginTop",!0),left:t.left-i.left-ce.css(r,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){var e=this.offsetParent;while(e&&"static"===ce.css(e,"position"))e=e.offsetParent;return e||J})}}),ce.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(t,i){var o="pageYOffset"===i;ce.fn[t]=function(e){return M(this,function(e,t,n){var r;if(y(e)?r=e:9===e.nodeType&&(r=e.defaultView),void 0===n)return r?r[i]:e[t];r?r.scrollTo(o?r.pageXOffset:n,o?n:r.pageYOffset):e[t]=n},t,e,arguments.length)}}),ce.each(["top","left"],function(e,n){ce.cssHooks[n]=Ye(le.pixelPosition,function(e,t){if(t)return t=Ge(e,n),_e.test(t)?ce(e).position()[n]+"px":t})}),ce.each({Height:"height",Width:"width"},function(a,s){ce.each({padding:"inner"+a,content:s,"":"outer"+a},function(r,o){ce.fn[o]=function(e,t){var n=arguments.length&&(r||"boolean"!=typeof e),i=r||(!0===e||!0===t?"margin":"border");return M(this,function(e,t,n){var r;return y(e)?0===o.indexOf("outer")?e["inner"+a]:e.document.documentElement["client"+a]:9===e.nodeType?(r=e.documentElement,Math.max(e.body["scroll"+a],r["scroll"+a],e.body["offset"+a],r["offset"+a],r["client"+a])):void 0===n?ce.css(e,t,i):ce.style(e,t,n,i)},s,n?e:void 0,n)}})}),ce.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(e,t){ce.fn[t]=function(e){return this.on(t,e)}}),ce.fn.extend({bind:function(e,t,n){return this.on(e,null,t,n)},unbind:function(e,t){return this.off(e,null,t)},delegate:function(e,t,n,r){return this.on(t,e,n,r)},undelegate:function(e,t,n){return 1===arguments.length?this.off(e,"**"):this.off(t,e||"**",n)},hover:function(e,t){return this.on("mouseenter",e).on("mouseleave",t||e)}}),ce.each("blur focus focusin focusout resize scroll click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup contextmenu".split(" "),function(e,n){ce.fn[n]=function(e,t){return 0 - + jQuery Migrate JavaScript Library A development tool to help migrate away from APIs and features that have been or will be removed from jQuery core Icons\Sigma\Extensions_32x32_Standard.png @@ -21,7 +21,7 @@ jQuery-Migrate jquery-migrate.js - https://code.jquery.com/jquery-migrate-3.4.0.min.js + https://code.jquery.com/jquery-migrate-3.4.1.min.js diff --git a/DNN Platform/JavaScript Libraries/jQueryMigrate/jquery-migrate.js b/DNN Platform/JavaScript Libraries/jQueryMigrate/jquery-migrate.js index f535eb1993e..29a4939df33 100644 --- a/DNN Platform/JavaScript Libraries/jQueryMigrate/jquery-migrate.js +++ b/DNN Platform/JavaScript Libraries/jQueryMigrate/jquery-migrate.js @@ -1,2 +1,2 @@ -/*! jQuery Migrate v3.4.0 | (c) OpenJS Foundation and other contributors | jquery.org/license */ -"undefined"==typeof jQuery.migrateMute&&(jQuery.migrateMute=!0),function(t){"use strict";"function"==typeof define&&define.amd?define(["jquery"],function(e){return t(e,window)}):"object"==typeof module&&module.exports?module.exports=t(require("jquery"),window):t(jQuery,window)}(function(s,n){"use strict";function e(e){return 0<=function(e,t){for(var r=/^(\d+)\.(\d+)\.(\d+)/,n=r.exec(e)||[],o=r.exec(t)||[],a=1;a<=3;a++){if(+n[a]>+o[a])return 1;if(+n[a]<+o[a])return-1}return 0}(s.fn.jquery,e)}s.migrateVersion="3.4.0";var t=Object.create(null),o=(s.migrateDisablePatches=function(){for(var e=0;e\x20\t\r\n\f]*)[^>]*)\/>/gi),_=(s.UNSAFE_restoreLegacyHtmlPrefilter=function(){s.migrateEnablePatches("self-closed-tags")},d(s,"htmlPrefilter",function(e){var t,r;return(r=(t=e).replace(O,"<$1>"))!==t&&C(t)!==C(r)&&i("self-closed-tags","HTML tags must be properly nested and closed: "+t),e.replace(O,"<$1>")},"self-closed-tags"),s.migrateDisablePatches("self-closed-tags"),s.fn.offset);return d(s.fn,"offset",function(){var e=this[0];return!e||e.nodeType&&e.getBoundingClientRect?_.apply(this,arguments):(i("offset-valid-elem","jQuery.fn.offset() requires a valid DOM element"),arguments.length?this:void 0)},"offset-valid-elem"),s.ajax&&(H=s.param,d(s,"param",function(e,t){var r=s.ajaxSettings&&s.ajaxSettings.traditional;return void 0===t&&r&&(i("param-ajax-traditional","jQuery.param() no longer uses jQuery.ajaxSettings.traditional"),t=r),H.call(this,e,t)},"param-ajax-traditional")),u(s.fn,"andSelf",s.fn.addBack,"andSelf","jQuery.fn.andSelf() is deprecated and removed, use jQuery.fn.addBack()"),s.Deferred&&(E=s.Deferred,M=[["resolve","done",s.Callbacks("once memory"),s.Callbacks("once memory"),"resolved"],["reject","fail",s.Callbacks("once memory"),s.Callbacks("once memory"),"rejected"],["notify","progress",s.Callbacks("memory"),s.Callbacks("memory")]],d(s,"Deferred",function(e){var a=E(),i=a.promise();function t(){var o=arguments;return s.Deferred(function(n){s.each(M,function(e,t){var r="function"==typeof o[e]&&o[e];a[t[1]](function(){var e=r&&r.apply(this,arguments);e&&"function"==typeof e.promise?e.promise().done(n.resolve).fail(n.reject).progress(n.notify):n[t[0]+"With"](this===i?n.promise():this,r?[e]:arguments)})}),o=null}).promise()}return u(a,"pipe",t,"deferred-pipe","deferred.pipe() is deprecated"),u(i,"pipe",t,"deferred-pipe","deferred.pipe() is deprecated"),e&&e.call(a,a),a},"deferred-pipe"),s.Deferred.exceptionHook=E.exceptionHook),s}); +/*! jQuery Migrate v3.4.1 | (c) OpenJS Foundation and other contributors | jquery.org/license */ +"undefined"==typeof jQuery.migrateMute&&(jQuery.migrateMute=!0),function(t){"use strict";"function"==typeof define&&define.amd?define(["jquery"],function(e){return t(e,window)}):"object"==typeof module&&module.exports?module.exports=t(require("jquery"),window):t(jQuery,window)}(function(s,n){"use strict";function e(e){return 0<=function(e,t){for(var r=/^(\d+)\.(\d+)\.(\d+)/,n=r.exec(e)||[],o=r.exec(t)||[],a=1;a<=3;a++){if(+o[a]<+n[a])return 1;if(+n[a]<+o[a])return-1}return 0}(s.fn.jquery,e)}s.migrateVersion="3.4.1";var t=Object.create(null);s.migrateDisablePatches=function(){for(var e=0;e\x20\t\r\n\f]*)[^>]*)\/>/gi;s.UNSAFE_restoreLegacyHtmlPrefilter=function(){s.migrateEnablePatches("self-closed-tags")},i(s,"htmlPrefilter",function(e){var t,r;return(r=(t=e).replace(F,"<$1>"))!==t&&T(t)!==T(r)&&u("self-closed-tags","HTML tags must be properly nested and closed: "+t),e.replace(F,"<$1>")},"self-closed-tags"),s.migrateDisablePatches("self-closed-tags");var D,W,_,I=s.fn.offset;return i(s.fn,"offset",function(){var e=this[0];return!e||e.nodeType&&e.getBoundingClientRect?I.apply(this,arguments):(u("offset-valid-elem","jQuery.fn.offset() requires a valid DOM element"),arguments.length?this:void 0)},"offset-valid-elem"),s.ajax&&(D=s.param,i(s,"param",function(e,t){var r=s.ajaxSettings&&s.ajaxSettings.traditional;return void 0===t&&r&&(u("param-ajax-traditional","jQuery.param() no longer uses jQuery.ajaxSettings.traditional"),t=r),D.call(this,e,t)},"param-ajax-traditional")),c(s.fn,"andSelf",s.fn.addBack,"andSelf","jQuery.fn.andSelf() is deprecated and removed, use jQuery.fn.addBack()"),s.Deferred&&(W=s.Deferred,_=[["resolve","done",s.Callbacks("once memory"),s.Callbacks("once memory"),"resolved"],["reject","fail",s.Callbacks("once memory"),s.Callbacks("once memory"),"rejected"],["notify","progress",s.Callbacks("memory"),s.Callbacks("memory")]],i(s,"Deferred",function(e){var a=W(),i=a.promise();function t(){var o=arguments;return s.Deferred(function(n){s.each(_,function(e,t){var r="function"==typeof o[e]&&o[e];a[t[1]](function(){var e=r&&r.apply(this,arguments);e&&"function"==typeof e.promise?e.promise().done(n.resolve).fail(n.reject).progress(n.notify):n[t[0]+"With"](this===i?n.promise():this,r?[e]:arguments)})}),o=null}).promise()}return c(a,"pipe",t,"deferred-pipe","deferred.pipe() is deprecated"),c(i,"pipe",t,"deferred-pipe","deferred.pipe() is deprecated"),e&&e.call(a,a),a},"deferred-pipe"),s.Deferred.exceptionHook=W.exceptionHook),s}); diff --git a/DNN Platform/Library/Application/Application.cs b/DNN Platform/Library/Application/Application.cs index 1aafbf0cea6..864296aa0e8 100644 --- a/DNN Platform/Library/Application/Application.cs +++ b/DNN Platform/Library/Application/Application.cs @@ -89,7 +89,7 @@ public virtual string SKU /// Gets the status of the DotnetNuke application. /// If the value is not be Stable, you will see the exactly status and version in page's title if allow display beta message in host setting. /// The value can be: None, Alpha, Beta, RC, Stable. - [Obsolete("Deprecated in Platform 9.7.0. Use 'DotNetNuke.Abstractions.Application.IApplicationInfo' with Dependency Injection instead. Scheduled for removal in v11.0.0.")] + [Obsolete("Deprecated in DotNetNuke 9.7.0. Use 'DotNetNuke.Abstractions.Application.IApplicationInfo' with Dependency Injection instead. Scheduled removal in v11.0.0.")] public ReleaseMode Status { get => (ReleaseMode)(this as IApplicationInfo).Status; } /// diff --git a/DNN Platform/Library/Application/ApplicationStatusInfo.cs b/DNN Platform/Library/Application/ApplicationStatusInfo.cs index 74b602388ed..a95d9dbce5b 100644 --- a/DNN Platform/Library/Application/ApplicationStatusInfo.cs +++ b/DNN Platform/Library/Application/ApplicationStatusInfo.cs @@ -1,285 +1,285 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information -namespace DotNetNuke.Application -{ - using System; - using System.IO; - using System.Web; - - using DotNetNuke.Abstractions.Application; - using DotNetNuke.Common.Utilities; - using DotNetNuke.Data; - using DotNetNuke.Framework.Providers; - using DotNetNuke.Instrumentation; - using DotNetNuke.Services.Upgrade; - - /// - public class ApplicationStatusInfo : IApplicationStatusInfo - { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(ApplicationStatusInfo)); - - private UpgradeStatus status = UpgradeStatus.Unknown; - private string applicationMapPath; - - private readonly IApplicationInfo applicationInfo; - - /// Initializes a new instance of the class. - /// The application info. - /// - /// This constructor is designed to be used with Dependency Injection. - /// - public ApplicationStatusInfo(IApplicationInfo applicationInfo) - { - this.applicationInfo = applicationInfo; - } - - /// - public UpgradeStatus Status - { - get - { - if (this.status != UpgradeStatus.Unknown && this.status != UpgradeStatus.Error) - { - return this.status; - } - - Logger.Trace("Getting application status"); - var tempStatus = UpgradeStatus.None; - - // first call GetProviderPath - this insures that the Database is Initialised correctly - // and also generates the appropriate error message if it cannot be initialised correctly - string strMessage = DataProvider.Instance().GetProviderPath(); - - // get current database version from DB - if (!strMessage.StartsWith("ERROR:")) - { - try - { - this.DatabaseVersion = DataProvider.Instance().GetVersion(); - } - catch (Exception ex) - { - Logger.Error(ex); - strMessage = "ERROR:" + ex.Message; - } - } - - if (strMessage.StartsWith("ERROR")) - { - if (this.IsInstalled()) - { - // Errors connecting to the database after an initial installation should be treated as errors. - tempStatus = UpgradeStatus.Error; - } - else - { - // An error that occurs before the database has been installed should be treated as a new install - tempStatus = UpgradeStatus.Install; - } - } - else if (this.DatabaseVersion == null) - { - // No Db Version so Install - tempStatus = UpgradeStatus.Install; - } - else - { - var version = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version; - if (version.Major > this.DatabaseVersion.Major) - { - // Upgrade Required (Major Version Upgrade) - tempStatus = UpgradeStatus.Upgrade; - } - else if (version.Major == this.DatabaseVersion.Major && version.Minor > this.DatabaseVersion.Minor) - { - // Upgrade Required (Minor Version Upgrade) - tempStatus = UpgradeStatus.Upgrade; - } - else if (version.Major == this.DatabaseVersion.Major && version.Minor == this.DatabaseVersion.Minor && - version.Build > this.DatabaseVersion.Build) - { - // Upgrade Required (Build Version Upgrade) - tempStatus = UpgradeStatus.Upgrade; - } - else if (version.Major == this.DatabaseVersion.Major && version.Minor == this.DatabaseVersion.Minor && - version.Build == this.DatabaseVersion.Build && this.IncrementalVersionExists(version)) - { - // Upgrade Required (Build Version Upgrade) - tempStatus = UpgradeStatus.Upgrade; - } - } - - this.status = tempStatus; - - Logger.Trace(string.Format("result of getting providerpath: {0}", strMessage)); - Logger.Trace("Application status is " + this.status); - - return this.status; - } - } - - /// - public Version DatabaseVersion { get; private set; } - - /// - public string ApplicationMapPath { get => this.applicationMapPath ?? (this.applicationMapPath = this.GetCurrentDomainDirectory()); } - - /// - public bool IsInstalled() - { - const int c_PassingScore = 4; - int installationdatefactor = Convert.ToInt32(this.HasInstallationDate() ? 1 : 0); - int dataproviderfactor = Convert.ToInt32(this.HasDataProviderLogFiles() ? 3 : 0); - int htmlmodulefactor = Convert.ToInt32(this.ModuleDirectoryExists("html") ? 2 : 0); - int portaldirectoryfactor = Convert.ToInt32(this.HasNonDefaultPortalDirectory() ? 2 : 0); - int localexecutionfactor = Convert.ToInt32(HttpContext.Current.Request.IsLocal ? c_PassingScore - 1 : 0); - - // This calculation ensures that you have a more than one item that indicates you have already installed DNN. - // While it is possible that you might not have an installation date or that you have deleted log files - // it is unlikely that you have removed every trace of an installation and yet still have a working install - bool isInstalled = (!this.IsInstallationURL()) && ((installationdatefactor + dataproviderfactor + htmlmodulefactor + portaldirectoryfactor + localexecutionfactor) >= c_PassingScore); - - // we need to tighten this check. We now are enforcing the existence of the InstallVersion value in web.config. If - // this value exists, then DNN was previously installed, and we should never try to re-install it - return isInstalled || this.HasInstallVersion(); - } - - /// Sets the status. - /// The status. - public void SetStatus(UpgradeStatus status) - { - this.status = status; - } - - /// - public void UpdateDatabaseVersion(Version version) - { - // update the version - DataProvider.Instance().UpdateDatabaseVersion(version.Major, version.Minor, version.Build, this.applicationInfo.Name); - this.DatabaseVersion = version; - } - - /// - public void UpdateDatabaseVersionIncrement(Version version, int increment) - { - // update the version and increment - DataProvider.Instance().UpdateDatabaseVersionIncrement(version.Major, version.Minor, version.Build, increment, DotNetNukeContext.Current.Application.Name); - this.DatabaseVersion = version; - } - - /// - public bool IncrementalVersionExists(Version version) - { - Provider currentdataprovider = Config.GetDefaultProvider("data"); - string providerpath = currentdataprovider.Attributes["providerPath"]; - - // If the provider path does not exist, then there can't be any log files - if (!string.IsNullOrEmpty(providerpath)) - { - providerpath = HttpRuntime.AppDomainAppPath + providerpath.Replace("~", string.Empty); - if (Directory.Exists(providerpath)) - { - var incrementalcount = Directory.GetFiles(providerpath, Upgrade.GetStringVersion(version) + ".*." + Upgrade.DefaultProvider).Length; - - if (incrementalcount > this.GetLastAppliedIteration(version)) - { - return true; - } - } - } - - return false; - } - - /// - public int GetLastAppliedIteration(Version version) - { - try - { - return DataProvider.Instance().GetLastAppliedIteration(version.Major, version.Minor, version.Build); - } - catch (Exception) - { - return 0; - } - } - - /// Determines whether current request is for install. - /// true if current request is for install; otherwise, false. - private bool IsInstallationURL() - { - string requestURL = HttpContext.Current.Request.RawUrl.ToLowerInvariant().Replace("\\", "/"); - return requestURL.Contains("/install.aspx") || requestURL.Contains("/installwizard.aspx"); - } - - /// Determines whether has installation date. - /// true if has installation date; otherwise, false. - private bool HasInstallationDate() - { - return Config.GetSetting("InstallationDate") != null; - } - - /// Determines whether has data provider log files. - /// true if has data provider log files; otherwise, false. - private bool HasDataProviderLogFiles() - { - Provider currentdataprovider = Config.GetDefaultProvider("data"); - string providerpath = currentdataprovider.Attributes["providerPath"]; - - // If the provider path does not exist, then there can't be any log files - if (!string.IsNullOrEmpty(providerpath)) - { - providerpath = HttpContext.Current.Server.MapPath(providerpath); - if (Directory.Exists(providerpath)) - { - return Directory.GetFiles(providerpath, "*.log.resources").Length > 0; - } - } - - return false; - } - - /// Check whether the modules directory is exists. - /// Name of the module. - /// true if the module directory exist, otherwise, false. - private bool ModuleDirectoryExists(string moduleName) - { - string dir = this.ApplicationMapPath + "\\desktopmodules\\" + moduleName; - return Directory.Exists(dir); - } - - /// Determines whether has portal directory except default portal directory in portal path. - /// true if has portal directory except default portal directory in portal path; otherwise, false. - private bool HasNonDefaultPortalDirectory() - { - string dir = this.ApplicationMapPath + "\\portals"; - if (Directory.Exists(dir)) - { - return Directory.GetDirectories(dir).Length > 1; - } - - return false; - } - - /// Determines whether has InstallVersion set. - /// true if has installation date; otherwise, false. - private bool HasInstallVersion() - { - return Config.GetSetting("InstallVersion") != null; - } - - /// Get the current domain directory. - /// returns the domain directory. - private string GetCurrentDomainDirectory() - { - var dir = AppDomain.CurrentDomain.BaseDirectory.Replace("/", "\\"); - if (dir.Length > 3 && dir.EndsWith("\\")) - { - dir = dir.Substring(0, dir.Length - 1); - } - - return dir; - } - } -} +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information +namespace DotNetNuke.Application +{ + using System; + using System.IO; + using System.Web; + + using DotNetNuke.Abstractions.Application; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Data; + using DotNetNuke.Framework.Providers; + using DotNetNuke.Instrumentation; + using DotNetNuke.Services.Upgrade; + + /// + public class ApplicationStatusInfo : IApplicationStatusInfo + { + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(ApplicationStatusInfo)); + + private readonly IApplicationInfo applicationInfo; + + private UpgradeStatus status = UpgradeStatus.Unknown; + private string applicationMapPath; + + /// Initializes a new instance of the class. + /// The application info. + /// + /// This constructor is designed to be used with Dependency Injection. + /// + public ApplicationStatusInfo(IApplicationInfo applicationInfo) + { + this.applicationInfo = applicationInfo; + } + + /// + public UpgradeStatus Status + { + get + { + if (this.status != UpgradeStatus.Unknown && this.status != UpgradeStatus.Error) + { + return this.status; + } + + Logger.Trace("Getting application status"); + var tempStatus = UpgradeStatus.None; + + // first call GetProviderPath - this insures that the Database is Initialised correctly + // and also generates the appropriate error message if it cannot be initialised correctly + string strMessage = DataProvider.Instance().GetProviderPath(); + + // get current database version from DB + if (!strMessage.StartsWith("ERROR:")) + { + try + { + this.DatabaseVersion = DataProvider.Instance().GetVersion(); + } + catch (Exception ex) + { + Logger.Error(ex); + strMessage = "ERROR:" + ex.Message; + } + } + + if (strMessage.StartsWith("ERROR")) + { + if (this.IsInstalled()) + { + // Errors connecting to the database after an initial installation should be treated as errors. + tempStatus = UpgradeStatus.Error; + } + else + { + // An error that occurs before the database has been installed should be treated as a new install + tempStatus = UpgradeStatus.Install; + } + } + else if (this.DatabaseVersion == null) + { + // No Db Version so Install + tempStatus = UpgradeStatus.Install; + } + else + { + var version = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version; + if (version.Major > this.DatabaseVersion.Major) + { + // Upgrade Required (Major Version Upgrade) + tempStatus = UpgradeStatus.Upgrade; + } + else if (version.Major == this.DatabaseVersion.Major && version.Minor > this.DatabaseVersion.Minor) + { + // Upgrade Required (Minor Version Upgrade) + tempStatus = UpgradeStatus.Upgrade; + } + else if (version.Major == this.DatabaseVersion.Major && version.Minor == this.DatabaseVersion.Minor && + version.Build > this.DatabaseVersion.Build) + { + // Upgrade Required (Build Version Upgrade) + tempStatus = UpgradeStatus.Upgrade; + } + else if (version.Major == this.DatabaseVersion.Major && version.Minor == this.DatabaseVersion.Minor && + version.Build == this.DatabaseVersion.Build && this.IncrementalVersionExists(version)) + { + // Upgrade Required (Build Version Upgrade) + tempStatus = UpgradeStatus.Upgrade; + } + } + + this.status = tempStatus; + + Logger.Trace(string.Format("result of getting providerpath: {0}", strMessage)); + Logger.Trace("Application status is " + this.status); + + return this.status; + } + } + + /// + public Version DatabaseVersion { get; private set; } + + /// + public string ApplicationMapPath { get => this.applicationMapPath ?? (this.applicationMapPath = this.GetCurrentDomainDirectory()); } + + /// + public bool IsInstalled() + { + const int c_PassingScore = 4; + int installationdatefactor = Convert.ToInt32(this.HasInstallationDate() ? 1 : 0); + int dataproviderfactor = Convert.ToInt32(this.HasDataProviderLogFiles() ? 3 : 0); + int htmlmodulefactor = Convert.ToInt32(this.ModuleDirectoryExists("html") ? 2 : 0); + int portaldirectoryfactor = Convert.ToInt32(this.HasNonDefaultPortalDirectory() ? 2 : 0); + int localexecutionfactor = Convert.ToInt32(HttpContext.Current.Request.IsLocal ? c_PassingScore - 1 : 0); + + // This calculation ensures that you have a more than one item that indicates you have already installed DNN. + // While it is possible that you might not have an installation date or that you have deleted log files + // it is unlikely that you have removed every trace of an installation and yet still have a working install + bool isInstalled = (!this.IsInstallationURL()) && ((installationdatefactor + dataproviderfactor + htmlmodulefactor + portaldirectoryfactor + localexecutionfactor) >= c_PassingScore); + + // we need to tighten this check. We now are enforcing the existence of the InstallVersion value in web.config. If + // this value exists, then DNN was previously installed, and we should never try to re-install it + return isInstalled || this.HasInstallVersion(); + } + + /// Sets the status. + /// The status. + public void SetStatus(UpgradeStatus status) + { + this.status = status; + } + + /// + public void UpdateDatabaseVersion(Version version) + { + // update the version + DataProvider.Instance().UpdateDatabaseVersion(version.Major, version.Minor, version.Build, this.applicationInfo.Name); + this.DatabaseVersion = version; + } + + /// + public void UpdateDatabaseVersionIncrement(Version version, int increment) + { + // update the version and increment + DataProvider.Instance().UpdateDatabaseVersionIncrement(version.Major, version.Minor, version.Build, increment, DotNetNukeContext.Current.Application.Name); + this.DatabaseVersion = version; + } + + /// + public bool IncrementalVersionExists(Version version) + { + Provider currentdataprovider = Config.GetDefaultProvider("data"); + string providerpath = currentdataprovider.Attributes["providerPath"]; + + // If the provider path does not exist, then there can't be any log files + if (!string.IsNullOrEmpty(providerpath)) + { + providerpath = HttpRuntime.AppDomainAppPath + providerpath.Replace("~", string.Empty); + if (Directory.Exists(providerpath)) + { + var incrementalcount = Directory.GetFiles(providerpath, Upgrade.GetStringVersion(version) + ".*." + Upgrade.DefaultProvider).Length; + + if (incrementalcount > this.GetLastAppliedIteration(version)) + { + return true; + } + } + } + + return false; + } + + /// + public int GetLastAppliedIteration(Version version) + { + try + { + return DataProvider.Instance().GetLastAppliedIteration(version.Major, version.Minor, version.Build); + } + catch (Exception) + { + return 0; + } + } + + /// Determines whether current request is for install. + /// true if current request is for install; otherwise, false. + private bool IsInstallationURL() + { + string requestURL = HttpContext.Current.Request.RawUrl.ToLowerInvariant().Replace("\\", "/"); + return requestURL.Contains("/install.aspx") || requestURL.Contains("/installwizard.aspx"); + } + + /// Determines whether has installation date. + /// true if has installation date; otherwise, false. + private bool HasInstallationDate() + { + return Config.GetSetting("InstallationDate") != null; + } + + /// Determines whether has data provider log files. + /// true if has data provider log files; otherwise, false. + private bool HasDataProviderLogFiles() + { + Provider currentdataprovider = Config.GetDefaultProvider("data"); + string providerpath = currentdataprovider.Attributes["providerPath"]; + + // If the provider path does not exist, then there can't be any log files + if (!string.IsNullOrEmpty(providerpath)) + { + providerpath = HttpContext.Current.Server.MapPath(providerpath); + if (Directory.Exists(providerpath)) + { + return Directory.GetFiles(providerpath, "*.log.resources").Length > 0; + } + } + + return false; + } + + /// Check whether the modules directory is exists. + /// Name of the module. + /// true if the module directory exist, otherwise, false. + private bool ModuleDirectoryExists(string moduleName) + { + string dir = this.ApplicationMapPath + "\\desktopmodules\\" + moduleName; + return Directory.Exists(dir); + } + + /// Determines whether has portal directory except default portal directory in portal path. + /// true if has portal directory except default portal directory in portal path; otherwise, false. + private bool HasNonDefaultPortalDirectory() + { + string dir = this.ApplicationMapPath + "\\portals"; + if (Directory.Exists(dir)) + { + return Directory.GetDirectories(dir).Length > 1; + } + + return false; + } + + /// Determines whether has InstallVersion set. + /// true if has installation date; otherwise, false. + private bool HasInstallVersion() + { + return Config.GetSetting("InstallVersion") != null; + } + + /// Get the current domain directory. + /// returns the domain directory. + private string GetCurrentDomainDirectory() + { + var dir = AppDomain.CurrentDomain.BaseDirectory.Replace("/", "\\"); + if (dir.Length > 3 && dir.EndsWith("\\")) + { + dir = dir.Substring(0, dir.Length - 1); + } + + return dir; + } + } +} diff --git a/DNN Platform/Library/Common/Extensions/HttpContextDependencyInjectionExtensions.cs b/DNN Platform/Library/Common/Extensions/HttpContextDependencyInjectionExtensions.cs index a7806b7e3f2..1038ea3d2f6 100644 --- a/DNN Platform/Library/Common/Extensions/HttpContextDependencyInjectionExtensions.cs +++ b/DNN Platform/Library/Common/Extensions/HttpContextDependencyInjectionExtensions.cs @@ -4,6 +4,7 @@ namespace DotNetNuke.Common.Extensions { + using System.Collections; using System.Web; using Microsoft.Extensions.DependencyInjection; @@ -11,56 +12,91 @@ namespace DotNetNuke.Common.Extensions /// Dependency injection extensions for HttpContext. public static class HttpContextDependencyInjectionExtensions { - /// Sets the service scope for the http context base. - /// The http context base. - /// The service scope. - public static void SetScope(this HttpContextBase httpContext, IServiceScope scope) - { - httpContext.Items[typeof(IServiceScope)] = scope; - } - /// Sets the service scope for the http context. /// The http context. /// The service scope. public static void SetScope(this HttpContext httpContext, IServiceScope scope) + => SetScope(new HttpContextWrapper(httpContext), scope); + + /// Sets the service scope for the http context base. + /// The http context base. + /// The service scope. + public static void SetScope(this HttpContextBase httpContext, IServiceScope scope) { - httpContext.Items[typeof(IServiceScope)] = scope; + if (!httpContext.Items.Contains(typeof(IServiceScope))) + { + httpContext.Items[typeof(IServiceScope)] = scope; + } } /// Clears the service scope for the http context. /// The http context on which to clear the service scope. public static void ClearScope(this HttpContext httpContext) + => ClearScope(new HttpContextWrapper(httpContext)); + + /// Clears the service scope for the http context. + /// The http context on which to clear the service scope. + public static void ClearScope(this HttpContextBase httpContext) { httpContext.Items.Remove(typeof(IServiceScope)); } + /// Gets the http context service scope. + /// The http context from which to get the scope from. + /// A service scope. + public static IServiceScope GetScope(this HttpContext httpContext) + => GetScope(new HttpContextWrapper(httpContext)); + /// Gets the http context base service scope. /// The http context base from which to get the scope from. /// A service scope. public static IServiceScope GetScope(this HttpContextBase httpContext) { - return GetScope(httpContext.Items); + var scope = httpContext.Items.GetScope(); + if (scope is not null || Globals.DependencyProvider is null) + { + return scope; + } + + var scopeLock = new object(); + const string ScopeLockName = "GetScope_lock"; + if (httpContext.Items.Contains(ScopeLockName)) + { + // another thread is adding the scope, try again + return GetScope(httpContext); + } + + httpContext.Items.Add(ScopeLockName, scopeLock); + lock (httpContext.Items[ScopeLockName]) + { + if (httpContext.Items[ScopeLockName] == scopeLock) + { + if (!httpContext.Items.Contains(typeof(IServiceScope))) + { + scope = Globals.DependencyProvider.CreateScope(); + httpContext.Items[typeof(IServiceScope)] = scope; + } + } + } + + if (scope is not null) + { + httpContext.AddOnRequestCompleted(DisposeScope); + return scope; + } + + return GetScope(httpContext); } - /// Gets the http context service scope. - /// The http context from which to get the scope from. - /// A service scope. - public static IServiceScope GetScope(this HttpContext httpContext) + private static IServiceScope GetScope(this IDictionary httpContextItems) { - return GetScope(httpContext.Items); + return httpContextItems[typeof(IServiceScope)] as IServiceScope; } - /// Gets the service scope from a collection of context items. - /// A dictionary of context items. - /// The found service scope. - internal static IServiceScope GetScope(System.Collections.IDictionary contextItems) + private static void DisposeScope(HttpContextBase httpContext) { - if (!contextItems.Contains(typeof(IServiceScope))) - { - return null; - } - - return contextItems[typeof(IServiceScope)] is IServiceScope scope ? scope : null; + httpContext.Items.GetScope()?.Dispose(); + httpContext.ClearScope(); } } } diff --git a/DNN Platform/Library/Common/Globals.cs b/DNN Platform/Library/Common/Globals.cs index e8659679151..e61ee6cb20a 100644 --- a/DNN Platform/Library/Common/Globals.cs +++ b/DNN Platform/Library/Common/Globals.cs @@ -40,6 +40,7 @@ namespace DotNetNuke.Common using DotNetNuke.Framework.JavaScriptLibraries; using DotNetNuke.Framework.Providers; using DotNetNuke.Instrumentation; + using DotNetNuke.Internal.SourceGenerators; using DotNetNuke.Security; using DotNetNuke.Security.Permissions; using DotNetNuke.Security.Roles; @@ -65,7 +66,7 @@ namespace DotNetNuke.Common "SA1310:Field names should not contain underscore", Justification = "Changing all these public fields names would be a massive breaking change only for a code style issue.")] [StandardModule] - public sealed class Globals + public sealed partial class Globals { /// Global role id for all users. /// -1. @@ -316,7 +317,7 @@ public static string ApplicationPath /// /// The application map path. /// - [Obsolete("Deprecated in 9.7.1. Use Dependency Injection to resolve 'DotNetNuke.Abstractions.IApplicationStatusInfo' instead. Scheduled for removal in v11.0.0.")] + [Obsolete("Deprecated in DotNetNuke 9.7.1. Use Dependency Injection to resolve 'DotNetNuke.Abstractions.IApplicationStatusInfo' instead. Scheduled removal in v11.0.0.")] public static string ApplicationMapPath => applicationStatusInfo.ApplicationMapPath; /// Gets the desktop module path. @@ -350,7 +351,7 @@ public static string ImagePath } /// Gets the database version. - [Obsolete("Deprecated in 9.7.1. Use Dependency Injection to resolve 'DotNetNuke.Abstractions.IApplicationStatusInfo' instead. Scheduled for removal in v11.0.0.")] + [Obsolete("Deprecated in DotNetNuke 9.7.1. Use Dependency Injection to resolve 'DotNetNuke.Abstractions.IApplicationStatusInfo' instead. Scheduled removal in v11.0.0.")] public static Version DataBaseVersion { get => applicationStatusInfo.DatabaseVersion; } /// Gets the host map path. @@ -415,12 +416,12 @@ public static string InstallPath /// Gets the status of application. /// - [Obsolete("Deprecated in 9.7.1. Use Dependency Injection to resolve 'DotNetNuke.Abstractions.IApplicationStatusInfo' instead. Scheduled for removal in v11.0.0.")] + [Obsolete("Deprecated in DotNetNuke 9.7.1. Use Dependency Injection to resolve 'DotNetNuke.Abstractions.IApplicationStatusInfo' instead. Scheduled removal in v11.0.0.")] public static UpgradeStatus Status { get => (UpgradeStatus)applicationStatusInfo.Status; } /// Gets image file types. /// Values read from ImageTypes List. If there is not List, default values will be jpg,jpeg,jpe,gif,bmp,png,svg,ico. - [Obsolete("Deprecated in v9.8.1, use ImageFileTypes instead, scheduled for removal in v11.")] + [Obsolete("Deprecated in DotNetNuke 9.8.1. Use ImageFileTypes instead. Scheduled removal in v11.0.0.")] [System.Diagnostics.CodeAnalysis.SuppressMessage( "StyleCop.CSharp.NamingRules", "SA1300:Element should begin with upper-case letter", @@ -528,8 +529,8 @@ public static void Redirect(string url, bool endResponse) /// If a 09.08.01.01.sqlDataProvider file exists for a provided version 09.08.01 this method will return true. /// The version. /// A value indicating whether any incremental sql script file exists. - [Obsolete("Deprecated in 9.7.1. Use Dependency Injection to resolve 'DotNetNuke.Abstractions.IApplicationStatusInfo' instead. Scheduled for removal in v11.0.0.")] - public static bool IncrementalVersionExists(Version version) => applicationStatusInfo.IncrementalVersionExists(version); + [DnnDeprecated(9, 7, 1, "Use Dependency Injection to resolve 'DotNetNuke.Abstractions.IApplicationStatusInfo' instead")] + public static partial bool IncrementalVersionExists(Version version) => applicationStatusInfo.IncrementalVersionExists(version); /// Builds the cross tab dataset. /// Name of the data set. @@ -542,8 +543,8 @@ public static void Redirect(string url, bool endResponse) /// The string value column. /// The numeric value column. /// the dataset instance. - [Obsolete("Deprecated in v9.8.1, scheduled for removal in v11")] - public static DataSet BuildCrossTabDataSet( + [DnnDeprecated(9, 8, 1, "No replacement")] + public static partial DataSet BuildCrossTabDataSet( string dataSetName, IDataReader result, string fixedColumns, @@ -569,8 +570,8 @@ public static DataSet BuildCrossTabDataSet( /// Name of the column, that contains the field value, if stored as number. Column must be contained in DataReader. /// culture of the field values in data reader's string value column. /// The generated DataSet. - [Obsolete("Deprecated in v9.8.1, scheduled for removal in v11")] - public static DataSet BuildCrossTabDataSet( + [DnnDeprecated(9, 8, 1, "No replacement")] + public static partial DataSet BuildCrossTabDataSet( string dataSetName, IDataReader result, string fixedColumns, @@ -900,21 +901,21 @@ public static bool FindDatabaseVersion(int major, int minor, int build) /// Updates the database version. /// The version. - [Obsolete("Deprecated in 9.7.1. Use Dependency Injection to resolve 'DotNetNuke.Abstractions.IApplicationStatusInfo' instead. Scheduled for removal in v11.0.0.")] - public static void UpdateDataBaseVersion(Version version) => applicationStatusInfo.UpdateDatabaseVersion(version); + [DnnDeprecated(9, 7, 1, "Use Dependency Injection to resolve 'DotNetNuke.Abstractions.IApplicationStatusInfo' instead")] + public static partial void UpdateDataBaseVersion(Version version) => applicationStatusInfo.UpdateDatabaseVersion(version); /// Updates the database version. /// The version. /// The increment (revision) number. - [Obsolete("Deprecated in 9.7.1. Use Dependency Injection to resolve 'DotNetNuke.Abstractions.IApplicationStatusInfo' instead. Scheduled for removal in v11.0.0.")] - public static void UpdateDataBaseVersionIncrement(Version version, int increment) => + [DnnDeprecated(9, 7, 1, "Use Dependency Injection to resolve 'DotNetNuke.Abstractions.IApplicationStatusInfo' instead")] + public static partial void UpdateDataBaseVersionIncrement(Version version, int increment) => applicationStatusInfo.UpdateDatabaseVersionIncrement(version, increment); /// Gets the last applied iteration (revision). /// The version for which to check the last revision. /// The last applied iteration (revision) for the requested version. - [Obsolete("Deprecated in 9.7.1. Use Dependency Injection to resolve 'DotNetNuke.Abstractions.IApplicationStatusInfo' instead. Scheduled for removal in v11.0.0.")] - public static int GetLastAppliedIteration(Version version) => + [DnnDeprecated(9, 7, 1, "Use Dependency Injection to resolve 'DotNetNuke.Abstractions.IApplicationStatusInfo' instead")] + public static partial int GetLastAppliedIteration(Version version) => applicationStatusInfo.GetLastAppliedIteration(version); /// Adds the port. @@ -1217,8 +1218,8 @@ public static int GetTotalRecords(ref IDataReader dr) /// Sets the status. /// The status. - [Obsolete("Deprecated in 9.7.1. Use Dependency Injection to resolve 'DotNetNuke.Abstractions.IApplicationStatusInfo' instead. Scheduled for removal in v11.0.0.")] - public static void SetStatus(UpgradeStatus status) => + [DnnDeprecated(9, 7, 1, "Use Dependency Injection to resolve 'DotNetNuke.Abstractions.IApplicationStatusInfo' instead")] + public static partial void SetStatus(UpgradeStatus status) => applicationStatusInfo.SetStatus((DotNetNuke.Abstractions.Application.UpgradeStatus)status); /// @@ -2263,8 +2264,8 @@ public static string FriendlyUrl(TabInfo tab, string path, string pageName) /// The path to format. /// The portal settings. /// The formatted (friendly) URL. - [Obsolete("Deprecated in Platform 9.4.3. Scheduled for removal in v11.0.0. Use the IPortalSettings overload")] - public static string FriendlyUrl(TabInfo tab, string path, PortalSettings settings) + [DnnDeprecated(9, 4, 3, "Use the IPortalSettings overload")] + public static partial string FriendlyUrl(TabInfo tab, string path, PortalSettings settings) { return FriendlyUrl(tab, path, (IPortalSettings)settings); } @@ -2292,8 +2293,8 @@ public static string FriendlyUrl(TabInfo tab, string path, IPortalSettings setti /// The page to include in the URL. /// The portal settings. /// The formatted (friendly) url. - [Obsolete("Deprecated in Platform 9.4.3. Scheduled for removal in v11.0.0. Use the IPortalSettings overload")] - public static string FriendlyUrl(TabInfo tab, string path, string pageName, PortalSettings settings) + [DnnDeprecated(9, 4, 3, "Use the IPortalSettings overload")] + public static partial string FriendlyUrl(TabInfo tab, string path, string pageName, PortalSettings settings) { return FriendlyUrl(tab, path, pageName, (IPortalSettings)settings); } @@ -2365,8 +2366,8 @@ public static TabType GetURLType(string url) /// The id of the module (unused). /// the url to import. /// If an internal link does not exist, an empty string is returned, otherwise the passed in url is returned as is. - [Obsolete("Deprecated in 9.8.1, moduleId is not used in the method, use the overload that takes only the url, scheduled removal in v11")] - public static string ImportUrl(int moduleId, string url) + [DnnDeprecated(9, 8, 1, "moduleId is not used in the method, use the overload that takes only the url")] + public static partial string ImportUrl(int moduleId, string url) { return ImportUrl(url); } @@ -2455,8 +2456,8 @@ public static string LoginURL(string returnUrl, bool overrideSetting) /// if set to true, show the login control on the current page, even if there is a login page defined for the site. /// The Portal Settings. /// Formatted URL. - [Obsolete("Deprecated in v9.8.1, use the overload that takes IPortalSettings instead, scheduled removal in v11.")] - public static string LoginURL(string returnUrl, bool overrideSetting, PortalSettings portalSettings) + [DnnDeprecated(9, 8, 1, "Use the overload that takes IPortalSettings instead")] + public static partial string LoginURL(string returnUrl, bool overrideSetting, PortalSettings portalSettings) { return LoginURL(returnUrl, overrideSetting, (IPortalSettings)portalSettings); } @@ -2528,8 +2529,8 @@ public static string UserProfileURL(int userId) /// Formatted URL. [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Obsolete("Deprecated in Platform 9.4.2. Scheduled removal in v11.0.0.")] - public static string NavigateURL() + [DnnDeprecated(9, 4, 2, "Use INavigationManager via dependency injection")] + public static partial string NavigateURL() { return navigationManager.NavigateURL(); } @@ -2539,8 +2540,8 @@ public static string NavigateURL() /// Formatted URL. [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Obsolete("Deprecated in Platform 9.4.2. Scheduled removal in v11.0.0.")] - public static string NavigateURL(int tabID) + [DnnDeprecated(9, 4, 2, "Use INavigationManager via dependency injection")] + public static partial string NavigateURL(int tabID) { return navigationManager.NavigateURL(tabID); } @@ -2551,8 +2552,8 @@ public static string NavigateURL(int tabID) /// Formatted URL. [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Obsolete("Deprecated in Platform 9.4.2. Scheduled removal in v11.0.0.")] - public static string NavigateURL(int tabID, bool isSuperTab) + [DnnDeprecated(9, 4, 2, "Use INavigationManager via dependency injection")] + public static partial string NavigateURL(int tabID, bool isSuperTab) { return navigationManager.NavigateURL(tabID, isSuperTab); } @@ -2562,8 +2563,8 @@ public static string NavigateURL(int tabID, bool isSuperTab) /// Formatted URL. [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Obsolete("Deprecated in Platform 9.4.2. Scheduled removal in v11.0.0.")] - public static string NavigateURL(string controlKey) + [DnnDeprecated(9, 4, 2, "Use INavigationManager via dependency injection")] + public static partial string NavigateURL(string controlKey) { return navigationManager.NavigateURL(controlKey); } @@ -2574,8 +2575,8 @@ public static string NavigateURL(string controlKey) /// Formatted URL. [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Obsolete("Deprecated in Platform 9.4.2. Scheduled removal in v11.0.0.")] - public static string NavigateURL(string controlKey, params string[] additionalParameters) + [DnnDeprecated(9, 4, 2, "Use INavigationManager via dependency injection")] + public static partial string NavigateURL(string controlKey, params string[] additionalParameters) { return navigationManager.NavigateURL(controlKey, additionalParameters); } @@ -2586,8 +2587,8 @@ public static string NavigateURL(string controlKey, params string[] additionalPa /// Formatted URL. [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Obsolete("Deprecated in Platform 9.4.2. Scheduled removal in v11.0.0.")] - public static string NavigateURL(int tabID, string controlKey) + [DnnDeprecated(9, 4, 2, "Use INavigationManager via dependency injection")] + public static partial string NavigateURL(int tabID, string controlKey) { return navigationManager.NavigateURL(tabID, controlKey); } @@ -2599,8 +2600,8 @@ public static string NavigateURL(int tabID, string controlKey) /// Formatted URL. [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Obsolete("Deprecated in Platform 9.4.2. Scheduled removal in v11.0.0.")] - public static string NavigateURL(int tabID, string controlKey, params string[] additionalParameters) + [DnnDeprecated(9, 4, 2, "Use INavigationManager via dependency injection")] + public static partial string NavigateURL(int tabID, string controlKey, params string[] additionalParameters) { return navigationManager.NavigateURL(tabID, controlKey, additionalParameters); } @@ -2613,8 +2614,8 @@ public static string NavigateURL(int tabID, string controlKey, params string[] a /// Formatted URL. [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Obsolete("Deprecated in Platform 9.4.2. Scheduled removal in v11.0.0.")] - public static string NavigateURL(int tabID, PortalSettings settings, string controlKey, params string[] additionalParameters) + [DnnDeprecated(9, 4, 2, "Use INavigationManager via dependency injection")] + public static partial string NavigateURL(int tabID, PortalSettings settings, string controlKey, params string[] additionalParameters) { return navigationManager.NavigateURL(tabID, settings, controlKey, additionalParameters); } @@ -2628,8 +2629,8 @@ public static string NavigateURL(int tabID, PortalSettings settings, string cont /// Formatted URL. [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Obsolete("Deprecated in Platform 9.4.2. Scheduled removal in v11.0.0.")] - public static string NavigateURL(int tabID, bool isSuperTab, PortalSettings settings, string controlKey, params string[] additionalParameters) + [DnnDeprecated(9, 4, 2, "Use INavigationManager via dependency injection")] + public static partial string NavigateURL(int tabID, bool isSuperTab, PortalSettings settings, string controlKey, params string[] additionalParameters) { return navigationManager.NavigateURL(tabID, isSuperTab, settings, controlKey, additionalParameters); } @@ -2642,8 +2643,8 @@ public static string NavigateURL(int tabID, bool isSuperTab, PortalSettings sett /// The language code. /// Any additional parameters. /// Formatted URL. - [Obsolete("Deprecated in Platform 9.4.2. Scheduled removal in v11.0.0.")] - public static string NavigateURL(int tabID, bool isSuperTab, PortalSettings settings, string controlKey, string language, params string[] additionalParameters) + [DnnDeprecated(9, 4, 2, "Use INavigationManager via dependency injection")] + public static partial string NavigateURL(int tabID, bool isSuperTab, PortalSettings settings, string controlKey, string language, params string[] additionalParameters) { return navigationManager.NavigateURL(tabID, isSuperTab, settings, controlKey, language, additionalParameters); } @@ -2657,8 +2658,8 @@ public static string NavigateURL(int tabID, bool isSuperTab, PortalSettings sett /// The page name to pass to . /// Any additional parameters. /// Formatted url. - [Obsolete("Deprecated in Platform 9.4.2. Scheduled removal in v11.0.0.")] - public static string NavigateURL(int tabID, bool isSuperTab, PortalSettings settings, string controlKey, string language, string pageName, params string[] additionalParameters) + [DnnDeprecated(9, 4, 2, "Use INavigationManager via dependency injection")] + public static partial string NavigateURL(int tabID, bool isSuperTab, PortalSettings settings, string controlKey, string language, string pageName, params string[] additionalParameters) { return navigationManager.NavigateURL(tabID, isSuperTab, settings, controlKey, language, pageName, additionalParameters); } @@ -2782,8 +2783,8 @@ public static string ResolveUrl(string url) /// Encodes the reserved characters. /// The query string. /// Encoded content. - [Obsolete("Deprecated in v9.8.1, use System.Net.WebUtility.UrlEncode instead, scheduled removal in v11.")] - public static string EncodeReservedCharacters(string queryString) + [DnnDeprecated(9, 8, 1, "Use System.Net.WebUtility.UrlEncode instead")] + public static partial string EncodeReservedCharacters(string queryString) { queryString = queryString.Replace("$", "%24"); queryString = queryString.Replace("&", "%26"); @@ -2801,8 +2802,8 @@ public static string EncodeReservedCharacters(string queryString) /// Dates to string. /// The date value. /// return value of input with SortableDateTimePattern. - [Obsolete(@"Deprecated in 9.8.1, use DateTime.ToString(""s"") instead, schedule removal in v11.")] - public static string DateToString(DateTime dateValue) + [DnnDeprecated(9, 8, 1, @"Use DateTime.ToString(""s"") instead")] + public static partial string DateToString(DateTime dateValue) { try { @@ -2827,8 +2828,8 @@ public static string DateToString(DateTime dateValue) /// The hash object. /// The default value. /// HashOject's value or DefaultValue if HashObject is null. - [Obsolete("Deprecated in v9.8.1, scheduled removal in v11")] - public static string GetHashValue(object hashObject, string defaultValue) + [DnnDeprecated(9, 8, 1, "No replacement")] + public static partial string GetHashValue(object hashObject, string defaultValue) { if (hashObject != null) { @@ -3089,8 +3090,8 @@ public static string GetHelpText(int moduleControlId) /// The help URL. /// The module config. /// The help url. - [Obsolete("Deprecated in 9.8.1, ModuleInfo is unused, use the overload that does not take a ModuleInfo, scheduled removal in v11.")] - public static string GetOnLineHelp(string helpUrl, ModuleInfo moduleConfig) + [DnnDeprecated(9, 8, 1, "ModuleInfo is unused, use the overload that does not take a ModuleInfo")] + public static partial string GetOnLineHelp(string helpUrl, ModuleInfo moduleConfig) { return GetOnLineHelp(helpUrl); } @@ -3147,8 +3148,8 @@ public static bool ValidateModuleInTab(int tabId, string moduleName) /// /// The String Source to deserialize. /// The deserialized Hashtable. - [Obsolete("Deprecated in 9.8.1, scheduled for removal in v11.")] - public static Hashtable DeserializeHashTableBase64(string source) + [DnnDeprecated(9, 8, 1, "No replacement")] + public static partial Hashtable DeserializeHashTableBase64(string source) { Hashtable objHashTable; if (!string.IsNullOrEmpty(source)) @@ -3185,8 +3186,8 @@ public static Hashtable DeserializeHashTableBase64(string source) /// /// The String Source to deserialize. /// The deserialized Hashtable. - [Obsolete("Deprecated in v9.8.1, this API was not meant to be public and only deserializes xml with a root of 'profile', scheduled removal in v11.")] - public static Hashtable DeserializeHashTableXml(string source) + [DnnDeprecated(9, 8, 1, "This API was not meant to be public and only deserializes xml with a root of 'profile'")] + public static partial Hashtable DeserializeHashTableXml(string source) { return XmlUtils.DeSerializeHashtable(source, "profile"); } @@ -3198,8 +3199,8 @@ public static Hashtable DeserializeHashTableXml(string source) /// /// The Hashtable to serialize. /// The serialized String. - [Obsolete("Deprecated in v9.8.1, scheduled removal in v11.")] - public static string SerializeHashTableBase64(Hashtable source) + [DnnDeprecated(9, 8, 1, "No replacement")] + public static partial string SerializeHashTableBase64(Hashtable source) { string strString; if (source.Count != 0) @@ -3236,8 +3237,8 @@ public static string SerializeHashTableBase64(Hashtable source) /// /// The Hashtable to serialize. /// The serialized String. - [Obsolete("Deprecated in v9.8.1, this method was never meant to be public and only works for 'profile' root namespace, scheduled removal in v11.")] - public static string SerializeHashTableXml(Hashtable source) + [DnnDeprecated(9, 8, 1, "This method was never meant to be public and only works for 'profile' root namespace")] + public static partial string SerializeHashTableXml(Hashtable source) { return XmlUtils.SerializeDictionary(source, "profile"); } @@ -3264,8 +3265,8 @@ public static bool IsHostTab(int tabId) /// Usage: ascx - <asp:Image ID="avatar" runat="server" CssClass="SkinObject" /> /// code behind - avatar.ImageUrl = string.Format(Globals.UserProfilePicFormattedUrl(), userInfo.UserID, 32, 32). /// - [Obsolete("Obsoleted in DNN 7.3.0 as it causes issues in SSL-offloading scenarios - please use UserProfilePicRelativeUrl instead.. Scheduled removal in v11.0.0.")] - public static string UserProfilePicFormattedUrl() + [DnnDeprecated(7, 3, 0, "It causes issues in SSL-offloading scenarios - please use UserProfilePicRelativeUrl instead", RemovalVersion = 11)] + public static partial string UserProfilePicFormattedUrl() { var avatarUrl = PortalController.Instance.GetCurrentPortalSettings().DefaultPortalAlias; if (string.IsNullOrEmpty(avatarUrl)) @@ -3290,8 +3291,8 @@ public static string UserProfilePicFormattedUrl() /// Usage: ascx - <asp:Image ID="avatar" runat="server" CssClass="SkinObject" /> /// code behind - avatar.ImageUrl = string.Format(Globals.UserProfilePicRelativeUrl(), userInfo.UserID, 32, 32). /// - [Obsolete("Deprecated in Platform 8.0.0. Please use UserController.Instance.GetUserProfilePictureUrl. Scheduled removal in v11.0.0.")] - public static string UserProfilePicRelativeUrl() + [DnnDeprecated(8, 0, 0, "Please use UserController.Instance.GetUserProfilePictureUrl", RemovalVersion = 11)] + public static partial string UserProfilePicRelativeUrl() { return UserProfilePicRelativeUrl(true); } @@ -3303,8 +3304,8 @@ public static string UserProfilePicRelativeUrl() /// Usage: ascx - <asp:Image ID="avatar" runat="server" CssClass="SkinObject" /> /// code behind - avatar.ImageUrl = string.Format(Globals.UserProfilePicRelativeUrl(), userInfo.UserID, 32, 32). /// - [Obsolete("Deprecated in Platform 8.0.0. Please use UserController.Instance.GetUserProfilePictureUrl. Scheduled removal in v11.0.0.")] - public static string UserProfilePicRelativeUrl(bool includeCdv) + [DnnDeprecated(8, 0, 0, "Please use UserController.Instance.GetUserProfilePictureUrl", RemovalVersion = 11)] + public static partial string UserProfilePicRelativeUrl(bool includeCdv) { const string query = "/DnnImageHandler.ashx?mode=profilepic&userId={0}&h={1}&w={2}"; var currentAlias = GetPortalSettings().PortalAlias.HTTPAlias; @@ -3328,8 +3329,8 @@ public static string UserProfilePicRelativeUrl(bool includeCdv) /// Formats an email address as a cloacked html link. /// The formatted email address. /// A cloacked html link. - [Obsolete("This function has been replaced by DotNetNuke.Common.Utilities.HtmlUtils.FormatEmail. Scheduled removal in v11.0.0.")] - public static string FormatEmail(string email) + [DnnDeprecated(7, 0, 0, "This function has been replaced by DotNetNuke.Common.Utilities.HtmlUtils.FormatEmail", RemovalVersion = 11)] + public static partial string FormatEmail(string email) { return HtmlUtils.FormatEmail(email); } @@ -3337,8 +3338,8 @@ public static string FormatEmail(string email) /// Formats a domain name including link. /// The domain name to format. /// The formatted domain name. - [Obsolete("This function has been replaced by DotNetNuke.Common.Utilities.HtmlUtils.FormatWebsite. Scheduled removal in v11.0.0.")] - public static string FormatWebsite(object website) + [DnnDeprecated(7, 0, 0, "This function has been replaced by DotNetNuke.Common.Utilities.HtmlUtils.FormatWebsite", RemovalVersion = 11)] + public static partial string FormatWebsite(object website) { return HtmlUtils.FormatWebsite(website); } @@ -3346,16 +3347,16 @@ public static string FormatWebsite(object website) /// Xml encodes an html string. /// The html to encode. /// The encoded html for usage in xml. - [Obsolete("This function has been replaced by DotNetNuke.Common.Utilities.XmlUtils.XMLEncode. Scheduled removal in v11.0.0.")] - public static string XMLEncode(string html) + [DnnDeprecated(7, 0, 0, "This function has been replaced by DotNetNuke.Common.Utilities.XmlUtils.XMLEncode", RemovalVersion = 11)] + public static partial string XMLEncode(string html) { return XmlUtils.XMLEncode(html); } /// Gets the database connection string. /// The database connection string. - [Obsolete("This function has been replaced by DotNetNuke.Common.Utilities.Config.GetConnectionString. Scheduled removal in v11.0.0.")] - public static string GetDBConnectionString() + [DnnDeprecated(7, 0, 0, "This function has been replaced by DotNetNuke.Common.Utilities.Config.GetConnectionString", RemovalVersion = 11)] + public static partial string GetDBConnectionString() { return Config.GetConnectionString(); } @@ -3365,8 +3366,8 @@ public static string GetDBConnectionString() /// The extensions to filter for. /// If true, adds 'None Specified' to the list. /// A list of file names. - [Obsolete("This method has been deprecated. Scheduled removal in v11.0.0.")] - public static ArrayList GetFileList( + [DnnDeprecated(7, 0, 0, "No replacement", RemovalVersion = 11)] + public static partial ArrayList GetFileList( DirectoryInfo currentDirectory, [Optional, DefaultParameterValue("")] // ERROR: Optional parameters aren't supported in C# string strExtensions, @@ -3404,8 +3405,8 @@ public static ArrayList GetFileList( /// Gets the subfolder path for a give filename path. /// The filename full path. /// The subfolder name. - [Obsolete("This method has been deprecated. Replaced by GetSubFolderPath(ByVal strFileNamePath As String, ByVal portaId as Integer). Scheduled removal in v11.0.0.")] - public static string GetSubFolderPath(string strFileNamePath) + [DnnDeprecated(7, 0, 0, "Replaced by GetSubFolderPath(string strFileNamePath, int portalId)", RemovalVersion = 11)] + public static partial string GetSubFolderPath(string strFileNamePath) { // Obtain PortalSettings from Current Context var portalSettings = PortalController.Instance.GetCurrentPortalSettings(); @@ -3427,8 +3428,8 @@ public static string GetSubFolderPath(string strFileNamePath) /// Gets a LinkClick url for tracking purposes. /// The actual link the LinkClick handler should point to. /// The formatted LinkClick url. - [Obsolete("This function has been obsoleted: Use Common.Globals.LinkClick() for proper handling of URLs. Scheduled removal in v11.0.0.")] - public static string LinkClickURL(string link) + [DnnDeprecated(7, 0, 0, "Use Common.Globals.LinkClick() for proper handling of URLs", RemovalVersion = 11)] + public static partial string LinkClickURL(string link) { PortalSettings portalSettings = PortalController.Instance.GetCurrentPortalSettings(); return LinkClick(link, portalSettings.ActiveTab.TabID, -1, false); @@ -3438,8 +3439,8 @@ public static string LinkClickURL(string link) /// IMPORTANT: It is highly recommended to use other forms of sql injection protection such as using SqlParameters or ORMs. /// The string to filter. /// The filtered string. - [Obsolete("Deprecated PreventSQLInjection Function to consolidate Security Filter functions in the PortalSecurity class. Scheduled removal in v11.0.0.")] - public static string PreventSQLInjection(string strSQL) + [DnnDeprecated(7, 0, 0, "Use Security Filter functions in the PortalSecurity class", RemovalVersion = 11)] + public static partial string PreventSQLInjection(string strSQL) { return PortalSecurity.Instance.InputFilter(strSQL, PortalSecurity.FilterFlag.NoSQL); } @@ -3452,8 +3453,8 @@ public static string PreventSQLInjection(string strSQL) /// since the connection string may not have been configured yet, which can occur during the installation /// wizard. /// - [Obsolete("Deprecated in 9.7.1. Use Dependency Injection to resolve 'DotNetNuke.Abstractions.IApplicationStatusInfo' instead. Scheduled for removal in v11.0.0.")] - internal static bool IsInstalled() => applicationStatusInfo.IsInstalled(); + [DnnDeprecated(9, 7, 1, "Use Dependency Injection to resolve 'DotNetNuke.Abstractions.IApplicationStatusInfo' instead")] + internal static partial bool IsInstalled() => applicationStatusInfo.IsInstalled(); /// Gets the culture code of the tab. /// The tab ID. diff --git a/DNN Platform/Library/Common/Lists/ListController.cs b/DNN Platform/Library/Common/Lists/ListController.cs index b88c8d7648a..18f37e3a351 100644 --- a/DNN Platform/Library/Common/Lists/ListController.cs +++ b/DNN Platform/Library/Common/Lists/ListController.cs @@ -16,16 +16,17 @@ namespace DotNetNuke.Common.Lists using DotNetNuke.Data; using DotNetNuke.Entities.Portals; using DotNetNuke.Entities.Users; + using DotNetNuke.Internal.SourceGenerators; using DotNetNuke.Services.Exceptions; using DotNetNuke.Services.Localization; using DotNetNuke.Services.Log.EventLog; using Microsoft.Extensions.DependencyInjection; /// Provides access to Dnn Lists. - public class ListController + public partial class ListController { /// The list of list types that are not localized. - [Obsolete("Deprecated in v9.8.1, use UnLocalizedLists instead, schedule removal in v11.")] + [Obsolete("Deprecated in DotNetNuke 9.8.1. Use UnLocalizedLists instead. Scheduled removal in v11.0.0.")] [System.Diagnostics.CodeAnalysis.SuppressMessage( "StyleCop.CSharp.MaintainabilityRules", "SA1401:Fields should be private", @@ -433,9 +434,9 @@ public void UpdateListSortOrder(int entryID, bool moveUp) /// Gets a collection of list entries. /// The name of the list to get. /// A collection of list entries. - [Obsolete("Obsoleted in 6.0.1 use IEnumerable GetListEntryInfoXXX(string) instead. Scheduled removal in v10.0.0.")] + [DnnDeprecated(6, 0, 1, "Use IEnumerable GetListEntryInfoXXX(string) instead", RemovalVersion = 10)] [EditorBrowsable(EditorBrowsableState.Never)] - public ListEntryInfoCollection GetListEntryInfoCollection(string listName) + public partial ListEntryInfoCollection GetListEntryInfoCollection(string listName) { return this.GetListEntryInfoCollection(listName, string.Empty, Null.NullInteger); } @@ -444,9 +445,9 @@ public ListEntryInfoCollection GetListEntryInfoCollection(string listName) /// The name of the list to get. /// The parent key. /// A collection of list entries. - [Obsolete("Obsoleted in 6.0.1 use IEnumerable GetListEntryInfoXXX(string, string, int) instead. Scheduled removal in v10.0.0.")] + [DnnDeprecated(6, 0, 1, "Use IEnumerable GetListEntryInfoXXX(string, string, int) instead", RemovalVersion = 10)] [EditorBrowsable(EditorBrowsableState.Never)] - public ListEntryInfoCollection GetListEntryInfoCollection(string listName, string parentKey) + public partial ListEntryInfoCollection GetListEntryInfoCollection(string listName, string parentKey) { return this.GetListEntryInfoCollection(listName, parentKey, Null.NullInteger); } @@ -456,9 +457,9 @@ public ListEntryInfoCollection GetListEntryInfoCollection(string listName, strin /// The parent key. /// The id of the site (portal) to get the list from. /// A collection of list entries. - [Obsolete("Obsoleted in 6.0.1 use IEnumerable GetListEntryInfoXXX(string, string, int) instead. Scheduled removal in v10.0.0.")] + [DnnDeprecated(6, 0, 1, "Use IEnumerable GetListEntryInfoXXX(string, string, int) instead", RemovalVersion = 10)] [EditorBrowsable(EditorBrowsableState.Never)] - public ListEntryInfoCollection GetListEntryInfoCollection(string listName, string parentKey, int portalId) + public partial ListEntryInfoCollection GetListEntryInfoCollection(string listName, string parentKey, int portalId) { var items = this.GetListEntryInfoItems(listName, parentKey, portalId); diff --git a/DNN Platform/Library/Common/Lists/ListEntryInfoCollection.cs b/DNN Platform/Library/Common/Lists/ListEntryInfoCollection.cs index 4cee6140243..cf68a7b684a 100644 --- a/DNN Platform/Library/Common/Lists/ListEntryInfoCollection.cs +++ b/DNN Platform/Library/Common/Lists/ListEntryInfoCollection.cs @@ -8,12 +8,13 @@ namespace DotNetNuke.Common.Lists using System.ComponentModel; using DotNetNuke.Instrumentation; + using DotNetNuke.Internal.SourceGenerators; /// Represents a collection of list entries. [Serializable] - [Obsolete("Obsoleted in 6.0.1. Replaced by using generic collections of ListEntryInfo objects. Scheduled removal in v10.0.0.")] + [DnnDeprecated(6, 0, 1, "Replaced by using generic collections of ListEntryInfo objects", RemovalVersion = 10)] [EditorBrowsable(EditorBrowsableState.Never)] - public class ListEntryInfoCollection : CollectionBase + public partial class ListEntryInfoCollection : CollectionBase { private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(ListEntryInfoCollection)); private readonly Hashtable keyIndexLookup = new Hashtable(); diff --git a/DNN Platform/Library/Common/Utilities/Config.cs b/DNN Platform/Library/Common/Utilities/Config.cs index f9d8ff6ac5b..83ba6b19af2 100644 --- a/DNN Platform/Library/Common/Utilities/Config.cs +++ b/DNN Platform/Library/Common/Utilities/Config.cs @@ -16,13 +16,14 @@ namespace DotNetNuke.Common.Utilities using DotNetNuke.Common.Utilities.Internal; using DotNetNuke.Framework.Providers; using DotNetNuke.Instrumentation; + using DotNetNuke.Internal.SourceGenerators; using DotNetNuke.Security; using DotNetNuke.Services.Exceptions; using Microsoft.Extensions.DependencyInjection; /// The Config class provides access to the web.config file. - public class Config + public partial class Config { private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(Config)); @@ -113,8 +114,8 @@ public static XmlDocument AddAppSetting(XmlDocument xmlDoc, string key, string v /// Adds a code subdirectory to the configuration. /// The name of the code subdirectory. - [Obsolete("Deprecated in DNN 9.11.1, use overload taking an IApplicationStatusInfo. Scheduled for removal in v11.")] - public static void AddCodeSubDirectory(string name) + [DnnDeprecated(9, 11, 1, "Use overload taking an IApplicationStatusInfo")] + public static partial void AddCodeSubDirectory(string name) { AddCodeSubDirectory( Globals.DependencyProvider.GetService() ?? new ApplicationStatusInfo(new Application()), @@ -165,8 +166,8 @@ public static void AddCodeSubDirectory(IApplicationStatusInfo appStatus, string } /// Creates a backup of the web.config file. - [Obsolete("Deprecated in DNN 9.11.1, use overload taking an IApplicationStatusInfo. Scheduled for removal in v11.")] - public static void BackupConfig() + [DnnDeprecated(9, 11, 1, "Use overload taking an IApplicationStatusInfo")] + public static partial void BackupConfig() { BackupConfig(Globals.DependencyProvider.GetService() ?? new ApplicationStatusInfo(new Application())); } @@ -252,8 +253,8 @@ public static string GetFcnMode() /// Returns the maximum file size allowed to be uploaded to the application in bytes. /// Size in bytes. - [Obsolete("Deprecated in DNN 9.11.1, use overload taking an IApplicationStatusInfo. Scheduled for removal in v11.")] - public static long GetMaxUploadSize() + [DnnDeprecated(9, 11, 1, "Use overload taking an IApplicationStatusInfo")] + public static partial long GetMaxUploadSize() { return GetMaxUploadSize( Globals.DependencyProvider.GetService() ?? new ApplicationStatusInfo(new Application())); @@ -294,8 +295,8 @@ public static long GetMaxUploadSize(IApplicationStatusInfo appStatus) /// Returns the maximum file size allowed to be uploaded based on the request filter limit. /// Size in megabytes. - [Obsolete("Deprecated in DNN 9.11.1, use overload taking an IApplicationStatusInfo. Scheduled for removal in v11.")] - public static long GetRequestFilterSize() + [DnnDeprecated(9, 11, 1, "Use overload taking an IApplicationStatusInfo")] + public static partial long GetRequestFilterSize() { return GetRequestFilterSize( Globals.DependencyProvider.GetService() ?? new ApplicationStatusInfo(new Application())); @@ -326,8 +327,8 @@ public static long GetRequestFilterSize(IApplicationStatusInfo appStatus) /// Sets the maximum file size allowed to be uploaded to the application in bytes. /// The new max upload size in bytes. - [Obsolete("Deprecated in DNN 9.11.1, use overload taking an IApplicationStatusInfo. Scheduled for removal in v11.")] - public static void SetMaxUploadSize(long newSize) + [DnnDeprecated(9, 11, 1, "Use overload taking an IApplicationStatusInfo")] + public static partial void SetMaxUploadSize(long newSize) { SetMaxUploadSize( Globals.DependencyProvider.GetService() ?? new ApplicationStatusInfo(new Application()), @@ -453,8 +454,8 @@ public static string GetObjectQualifer() /// Gets the authentication cookie timeout value. /// The timeout value. - [Obsolete("Deprecated in DNN 9.11.1, use overload taking an IApplicationStatusInfo. Scheduled for removal in v11.")] - public static int GetAuthCookieTimeout() + [DnnDeprecated(9, 11, 1, "Use overload taking an IApplicationStatusInfo")] + public static partial int GetAuthCookieTimeout() { return GetAuthCookieTimeout( Globals.DependencyProvider.GetService() ?? new ApplicationStatusInfo(new Application())); @@ -487,8 +488,8 @@ public static int GetAuthCookieTimeout(IApplicationStatusInfo appStatus) /// Gets optional persistent cookie timeout value from web.config. /// The persistent cookie value. /// Allows users to override default asp.net values. - [Obsolete("Deprecated in DNN 9.11.1, use overload taking an IApplicationStatusInfo. Scheduled for removal in v11.")] - public static int GetPersistentCookieTimeout() + [DnnDeprecated(9, 11, 1, "Use overload taking an IApplicationStatusInfo")] + public static partial int GetPersistentCookieTimeout() { return GetPersistentCookieTimeout( Globals.DependencyProvider.GetService() ?? new ApplicationStatusInfo(new Application())); @@ -555,16 +556,16 @@ public static XmlDocument Load(IApplicationStatusInfo appStatus) /// Loads the web.config file into an XML document. /// The configuration XML document. - [Obsolete("Deprecated in DNN 9.11.1, use overload taking an IApplicationStatusInfo. Scheduled for removal in v11.")] - public static XmlDocument Load() + [DnnDeprecated(9, 11, 1, "Use overload taking an IApplicationStatusInfo")] + public static partial XmlDocument Load() { return Load("web.config"); } /// Gets the currently configured custom error mode. /// The currently configured custom error mode string. - [Obsolete("Deprecated in DNN 9.11.1, use overload taking an IApplicationStatusInfo. Scheduled for removal in v11.")] - public static string GetCustomErrorMode() + [DnnDeprecated(9, 11, 1, "Use overload taking an IApplicationStatusInfo")] + public static partial string GetCustomErrorMode() { return GetCustomErrorMode( Globals.DependencyProvider.GetService() ?? new ApplicationStatusInfo(new Application())); @@ -592,8 +593,8 @@ public static string GetCustomErrorMode(IApplicationStatusInfo appStatus) /// Loads a configuration file as an XML document. /// The configuration file name. /// The configuration as an XML document. - [Obsolete("Deprecated in DNN 9.11.1, use overload taking an IApplicationStatusInfo. Scheduled for removal in v11.")] - public static XmlDocument Load(string filename) + [DnnDeprecated(9, 11, 1, "Use overload taking an IApplicationStatusInfo")] + public static partial XmlDocument Load(string filename) { return Load( Globals.DependencyProvider.GetService() ?? new ApplicationStatusInfo(new Application()), @@ -629,8 +630,8 @@ public static XmlDocument Load(IApplicationStatusInfo appStatus, string filename /// Removes a code subdirectory for the web.config file. /// The name of the code subdirectory. - [Obsolete("Deprecated in DNN 9.11.1, use overload taking an IApplicationStatusInfo. Scheduled for removal in v11.")] - public static void RemoveCodeSubDirectory(string name) + [DnnDeprecated(9, 11, 1, "Use overload taking an IApplicationStatusInfo")] + public static partial void RemoveCodeSubDirectory(string name) { RemoveCodeSubDirectory( Globals.DependencyProvider.GetService() ?? new ApplicationStatusInfo(new Application()), @@ -690,8 +691,8 @@ public static string Save(IApplicationStatusInfo appStatus, XmlDocument xmlDoc) /// Save the web.config file. /// The configuration as an XML document. /// An empty string upon success or the error message upon failure. - [Obsolete("Deprecated in DNN 9.11.1, use overload taking an IApplicationStatusInfo. Scheduled for removal in v11.")] - public static string Save(XmlDocument xmlDoc) + [DnnDeprecated(9, 11, 1, "Use overload taking an IApplicationStatusInfo")] + public static partial string Save(XmlDocument xmlDoc) { return Save(xmlDoc, "web.config"); } @@ -700,8 +701,8 @@ public static string Save(XmlDocument xmlDoc) /// The configuration as an XML document. /// The file name to save to. /// An empty string upon success or the error message upon failure. - [Obsolete("Deprecated in DNN 9.11.1, use overload taking an IApplicationStatusInfo. Scheduled for removal in v11.")] - public static string Save(XmlDocument xmlDoc, string filename) + [DnnDeprecated(9, 11, 1, "Use overload taking an IApplicationStatusInfo")] + public static partial string Save(XmlDocument xmlDoc, string filename) { return Save( Globals.DependencyProvider.GetService() ?? new ApplicationStatusInfo(new Application()), @@ -777,8 +778,8 @@ public static string Save(IApplicationStatusInfo appStatus, XmlDocument xmlDoc, /// Touches the web.config file to force the application to reload. /// A value indicating whether the operation succeeded. - [Obsolete("Deprecated in DNN 9.11.1, use overload taking an IApplicationStatusInfo. Scheduled for removal in v11.")] - public static bool Touch() + [DnnDeprecated(9, 11, 1, "Use overload taking an IApplicationStatusInfo")] + public static partial bool Touch() { return Touch( Globals.DependencyProvider.GetService() ?? new ApplicationStatusInfo(new Application())); @@ -805,8 +806,8 @@ public static bool Touch(IApplicationStatusInfo appStatus) /// Updates the database connection string. /// The connection string value. - [Obsolete("Deprecated in DNN 9.11.1, use overload taking an IApplicationStatusInfo. Scheduled for removal in v11.")] - public static void UpdateConnectionString(string conn) + [DnnDeprecated(9, 11, 1, "Use overload taking an IApplicationStatusInfo")] + public static partial void UpdateConnectionString(string conn) { UpdateConnectionString( Globals.DependencyProvider.GetService() ?? new ApplicationStatusInfo(new Application()), @@ -837,8 +838,8 @@ public static void UpdateConnectionString(IApplicationStatusInfo appStatus, stri /// The data provider name. /// The database owner, usually dbo. /// The object qualifier if multiple Dnn instance run under the same database (not recommended). - [Obsolete("Deprecated in DNN 9.11.1, use overload taking an IApplicationStatusInfo. Scheduled for removal in v11.")] - public static void UpdateDataProvider(string name, string databaseOwner, string objectQualifier) + [DnnDeprecated(9, 11, 1, "Use overload taking an IApplicationStatusInfo")] + public static partial void UpdateDataProvider(string name, string databaseOwner, string objectQualifier) { UpdateDataProvider( Globals.DependencyProvider.GetService() ?? new ApplicationStatusInfo(new Application()), @@ -868,8 +869,8 @@ public static void UpdateDataProvider(IApplicationStatusInfo appStatus, string n /// Updates the specified upgrade connection string. /// The connection string name. /// The new value for the connection string. - [Obsolete("Deprecated in DNN 9.11.1, use overload taking an IApplicationStatusInfo. Scheduled for removal in v11.")] - public static void UpdateUpgradeConnectionString(string name, string upgradeConnectionString) + [DotNetNuke.Internal.SourceGenerators.DnnDeprecated(9, 11, 1, "Use overload taking an IApplicationStatusInfo")] + public static partial void UpdateUpgradeConnectionString(string name, string upgradeConnectionString) { UpdateUpgradeConnectionString( Globals.DependencyProvider.GetService() ?? new ApplicationStatusInfo(new Application()), @@ -895,8 +896,8 @@ public static void UpdateUpgradeConnectionString(IApplicationStatusInfo appStatu /// Updates the unique machine key. Warning: Do not change this after installation unless you know what your are doing. /// An empty string upon success or an error message upon failure. - [Obsolete("Deprecated in DNN 9.11.1, use overload taking an IApplicationStatusInfo. Scheduled for removal in v11.")] - public static string UpdateMachineKey() + [DnnDeprecated(9, 11, 1, "Use overload taking an IApplicationStatusInfo")] + public static partial string UpdateMachineKey() { return UpdateMachineKey( Globals.DependencyProvider.GetService() ?? new ApplicationStatusInfo(new Application())); @@ -953,8 +954,8 @@ public static XmlDocument UpdateMachineKey(XmlDocument xmlConfig) /// Updates the validation key. WARNING: Do not call this API unless you now what you are doing. /// An empty string upon success or an error message upon failure. - [Obsolete("Deprecated in DNN 9.11.1, use overload taking an IApplicationStatusInfo. Scheduled for removal in v11.")] - public static string UpdateValidationKey() + [DnnDeprecated(9, 11, 1, "Use overload taking an IApplicationStatusInfo")] + public static partial string UpdateValidationKey() { return UpdateValidationKey( Globals.DependencyProvider.GetService() ?? new ApplicationStatusInfo(new Application())); @@ -1012,8 +1013,8 @@ public static XmlDocument UpdateValidationKey(XmlDocument xmlConfig) /// The config.file to get the path for. /// fully qualified path to the file. /// Will copy the file from the template directory as required. - [Obsolete("Deprecated in DNN 9.11.1, use overload taking an IApplicationStatusInfo. Scheduled for removal in v11.")] - public static string GetPathToFile(ConfigFileType file) + [DnnDeprecated(9, 11, 1, "Use overload taking an IApplicationStatusInfo")] + public static partial string GetPathToFile(ConfigFileType file) { return GetPathToFile(file, false); } @@ -1033,8 +1034,8 @@ public static string GetPathToFile(IApplicationStatusInfo appStatus, ConfigFileT /// force an overwrite of the config file. /// fully qualified path to the file. /// Will copy the file from the template directory as required. - [Obsolete("Deprecated in DNN 9.11.1, use overload taking an IApplicationStatusInfo. Scheduled for removal in v11.")] - public static string GetPathToFile(ConfigFileType file, bool overwrite) + [DnnDeprecated(9, 11, 1, "Use overload taking an IApplicationStatusInfo")] + public static partial string GetPathToFile(ConfigFileType file, bool overwrite) { return GetPathToFile( Globals.DependencyProvider.GetService() ?? new ApplicationStatusInfo(new Application()), @@ -1069,8 +1070,8 @@ public static string GetPathToFile(IApplicationStatusInfo appStatus, ConfigFileT /// UpdateInstallVersion, but only if the setting does not already exist. /// The version to update to. /// An empty string upon success or an error message upon failure. - [Obsolete("Deprecated in DNN 9.11.1, use overload taking an IApplicationStatusInfo. Scheduled for removal in v11.")] - public static string UpdateInstallVersion(Version version) + [DnnDeprecated(9, 11, 1, "Use overload taking an IApplicationStatusInfo")] + public static partial string UpdateInstallVersion(Version version) { return UpdateInstallVersion( Globals.DependencyProvider.GetService() ?? new ApplicationStatusInfo(new Application()), @@ -1110,7 +1111,6 @@ public static string UpdateInstallVersion(IApplicationStatusInfo appStatus, Vers // save a copy of the web.config strError += Save(appStatus, xmlConfig, GetTimestampedBackupPath(appStatus, "web_.config")); - // save the web.config strError += Save(appStatus, xmlConfig); } @@ -1129,8 +1129,8 @@ public static bool IsNet45OrNewer() /// Adds the File Change Notification (FCN) mode to the web.config if it does not yet exist. /// The file change notification (FNC) mode. /// Always an empty string. - [Obsolete("Deprecated in DNN 9.11.1, use overload taking an IApplicationStatusInfo. Scheduled for removal in v11.")] - public static string AddFCNMode(FcnMode fcnMode) + [DnnDeprecated(9, 11, 1, "Use overload taking an IApplicationStatusInfo")] + public static partial string AddFCNMode(FcnMode fcnMode) { return AddFCNMode( Globals.DependencyProvider.GetService() ?? new ApplicationStatusInfo(new Application()), diff --git a/DNN Platform/Library/Common/Utilities/DateUtils.cs b/DNN Platform/Library/Common/Utilities/DateUtils.cs index 9b204c36546..9ac423b8508 100644 --- a/DNN Platform/Library/Common/Utilities/DateUtils.cs +++ b/DNN Platform/Library/Common/Utilities/DateUtils.cs @@ -4,12 +4,13 @@ namespace DotNetNuke.Common.Utilities { using System; - + using DotNetNuke.Data; + using DotNetNuke.Internal.SourceGenerators; using DotNetNuke.Services.Localization; /// Provides utility methods to work with Dates. - public class DateUtils + public partial class DateUtils { private static DateTime lastUpdateUtc = DateTime.MinValue; private static DateTime lastUpdateLocal = DateTime.MinValue; @@ -20,8 +21,8 @@ public class DateUtils /// Gets the database time. /// Date/time of the database in UTC. - [Obsolete("Deprecated in DNN 9.1.0. Replaced by GetDatabaseUtcTime. Scheduled removal in v11.0.0.")] - public static DateTime GetDatabaseTime() + [DnnDeprecated(9, 1, 0, "Replaced by GetDatabaseUtcTime")] + public static partial DateTime GetDatabaseTime() { return GetDatabaseUtcTime(); } diff --git a/DNN Platform/Library/Common/Utilities/FileSystemExtensions.cs b/DNN Platform/Library/Common/Utilities/FileSystemExtensions.cs index d931a6bc5cb..b88ff0d8f4f 100644 --- a/DNN Platform/Library/Common/Utilities/FileSystemExtensions.cs +++ b/DNN Platform/Library/Common/Utilities/FileSystemExtensions.cs @@ -2,14 +2,18 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information -namespace DotNetNuke.Common.Utilities +namespace DotNetNuke.Common.Utilities { using System; using System.Collections.Generic; using System.IO; using System.IO.Compression; - public static class FileSystemExtensions + using DotNetNuke.Internal.SourceGenerators; + + using ICSharpCode.SharpZipLib.Zip; + + public static partial class FileSystemExtensions { public static void CheckZipEntry(this ZipArchiveEntry input) { @@ -53,8 +57,8 @@ public static IEnumerable FileEntries(this ZipArchive zip) } } - [Obsolete("Deprecated in 9.11.0, will be removed in 11.0.0, replaced with .net compression types.")] - public static void CheckZipEntry(this ICSharpCode.SharpZipLib.Zip.ZipEntry input) + [DnnDeprecated(9, 11, 0, "Replaced with .NET compression types.")] + public static partial void CheckZipEntry(this ZipEntry input) { var fullName = input.Name.Replace('\\', '/'); if (fullName.StartsWith("..") || fullName.Contains("/../")) @@ -62,5 +66,5 @@ public static void CheckZipEntry(this ICSharpCode.SharpZipLib.Zip.ZipEntry input throw new Exception("Illegal Zip File"); } } - } -} + } +} diff --git a/DNN Platform/Library/Common/Utilities/FileSystemUtils.cs b/DNN Platform/Library/Common/Utilities/FileSystemUtils.cs index c9705dd3149..57254313a61 100644 --- a/DNN Platform/Library/Common/Utilities/FileSystemUtils.cs +++ b/DNN Platform/Library/Common/Utilities/FileSystemUtils.cs @@ -12,6 +12,7 @@ namespace DotNetNuke.Common.Utilities using DotNetNuke.Abstractions.Application; using DotNetNuke.Instrumentation; + using DotNetNuke.Internal.SourceGenerators; using ICSharpCode.SharpZipLib.Zip; using Microsoft.Extensions.DependencyInjection; @@ -22,7 +23,7 @@ namespace DotNetNuke.Common.Utilities /// /// File System utilities. /// - public class FileSystemUtils + public partial class FileSystemUtils { private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(FileSystemUtils)); @@ -430,8 +431,8 @@ public static string FixPath(string input) /// The path to the file to add. /// Name of the file to use in the zip entry. /// The name of the folder to use in the zip entry.. - [Obsolete("Deprecated in 9.11.0, will be removed in 11.0.0, replaced with .net compression types.")] - public static void AddToZip(ref ZipOutputStream zipFile, string filePath, string fileName, string folder) + [DnnDeprecated(9, 11, 0, "Replaced with .NET compression types.")] + public static partial void AddToZip(ref ZipOutputStream zipFile, string filePath, string fileName, string folder) { FileStream fs = null; try @@ -479,8 +480,8 @@ public static void AddToZip(ref ZipOutputStream zipFile, string filePath, string /// /// The zip stream. /// The destination path to extract to. - [Obsolete("Deprecated in 9.11.0, will be removed in 11.0.0, replaced with .net compression types.")] - public static void UnzipResources(ZipInputStream zipStream, string destPath) + [DnnDeprecated(9, 11, 0, "Replaced with .NET compression types.")] + public static partial void UnzipResources(ZipInputStream zipStream, string destPath) { try { diff --git a/DNN Platform/Library/Common/Utilities/HtmlUtils.cs b/DNN Platform/Library/Common/Utilities/HtmlUtils.cs index 58353a1030b..8dc0b563ca2 100644 --- a/DNN Platform/Library/Common/Utilities/HtmlUtils.cs +++ b/DNN Platform/Library/Common/Utilities/HtmlUtils.cs @@ -10,10 +10,11 @@ namespace DotNetNuke.Common.Utilities using System.Text.RegularExpressions; using System.Web; + using DotNetNuke.Internal.SourceGenerators; using DotNetNuke.Services.Upgrade; /// HtmlUtils is a Utility class that provides Html Utility methods. - public class HtmlUtils + public partial class HtmlUtils { // Create Regular Expression objects private const string PunctuationMatch = "[~!#\\$%\\^&*\\(\\)-+=\\{\\[\\}\\]\\|;:\\x22'<,>\\.\\?\\\\\\t\\r\\v\\f\\n]"; @@ -228,8 +229,8 @@ public static string Shorten(string txt, int length, string suffix) /// The HTML content to clean up. /// Indicates whether to replace the Entity by a space () or nothing (). /// The cleaned up string. - [Obsolete("This method has been deprecated. Please use System.Web.HtmlUtility.HtmlDecode. Scheduled removal in v11.0.0.")] - public static string StripEntities(string html, bool retainSpace) + [DnnDeprecated(7, 0, 0, "Please use System.Web.HtmlUtility.HtmlDecode", RemovalVersion = 11)] + public static partial string StripEntities(string html, bool retainSpace) { var repString = retainSpace ? " " : string.Empty; diff --git a/DNN Platform/Library/Common/Utilities/IPathUtils.cs b/DNN Platform/Library/Common/Utilities/IPathUtils.cs index 3a24dccc5d3..91ca7c4ff83 100644 --- a/DNN Platform/Library/Common/Utilities/IPathUtils.cs +++ b/DNN Platform/Library/Common/Utilities/IPathUtils.cs @@ -33,7 +33,7 @@ public interface IPathUtils /// The user identifier. /// The UserFolderElement to get. /// The element from the user folder path. - [Obsolete("Deprecated in DNN 6.2. No replacement, this should have been internal only. Scheduled removal in v10.0.0.")] + [Obsolete("Deprecated in DotNetNuke 6.2.0. No replacement, this should have been internal only. Scheduled removal in v10.0.0.")] string GetUserFolderPathElement(int userID, PathUtils.UserFolderElement mode); /// Checks if a folder is a default protected folder. diff --git a/DNN Platform/Library/Common/Utilities/XmlUtils.cs b/DNN Platform/Library/Common/Utilities/XmlUtils.cs index 39a7143a286..a7b84cda4b9 100644 --- a/DNN Platform/Library/Common/Utilities/XmlUtils.cs +++ b/DNN Platform/Library/Common/Utilities/XmlUtils.cs @@ -18,10 +18,11 @@ namespace DotNetNuke.Common.Utilities using DotNetNuke.Entities.Modules; using DotNetNuke.Entities.Tabs; using DotNetNuke.Instrumentation; + using DotNetNuke.Internal.SourceGenerators; using DotNetNuke.Security.Permissions; /// The XmlUtils class provides Shared/Static methods for manipulating xml files. - public class XmlUtils + public partial class XmlUtils { private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(XmlUtils)); @@ -763,8 +764,8 @@ public static string XPathLiteral(string value) return sb.ToString(); } - [Obsolete("This method is obsolete. Use .Net XmlDocument.Load instead. Scheduled removal in v11.0.0.")] - public static XmlDocument GetXMLContent(string contentUrl) + [DnnDeprecated(7, 0, 0, "Use XmlDocument.Load instead", RemovalVersion = 11)] + public static partial XmlDocument GetXMLContent(string contentUrl) { // This function reads an Xml document via a Url and returns it as an XmlDocument object var functionReturnValue = new XmlDocument { XmlResolver = null }; diff --git a/DNN Platform/Library/Data/DataProvider.cs b/DNN Platform/Library/Data/DataProvider.cs index 59e9f8bfce7..8186f4c726c 100644 --- a/DNN Platform/Library/Data/DataProvider.cs +++ b/DNN Platform/Library/Data/DataProvider.cs @@ -23,12 +23,13 @@ namespace DotNetNuke.Data using DotNetNuke.Entities.Tabs; using DotNetNuke.Entities.Users; using DotNetNuke.Instrumentation; + using DotNetNuke.Internal.SourceGenerators; using DotNetNuke.Security; using DotNetNuke.Services.Exceptions; using DotNetNuke.Services.Search.Entities; using Microsoft.ApplicationBlocks.Data; - public abstract class DataProvider + public abstract partial class DataProvider { private const int DuplicateKey = 2601; @@ -275,7 +276,7 @@ public virtual string GetProviderPath() } /// Tests the Database Connection using the database connection config. - /// The connection string, or an error message (prefixed with "ERROR:"), or if is . + /// The connection string, or an error message (prefixed with "ERROR:"), or if is . public virtual string TestDatabaseConnection(DbConnectionStringBuilder builder, string owner, string qualifier) { var sqlBuilder = builder as SqlConnectionStringBuilder; @@ -403,8 +404,8 @@ public virtual int UpdateServerActivity(string serverName, string iisAppName, Da return this.ExecuteScalar("UpdateServerActivity", serverName, iisAppName, createdDate, lastActivityDate, pingFailureCount, enabled); } - [Obsolete("Deprecated in Platform 7.4.0, please use CreatePortal version that contain's culturecode. Scheduled removal in v10.0.0.")] - public virtual int CreatePortal(string portalname, string currency, DateTime expiryDate, double hostFee, double hostSpace, int pageQuota, int userQuota, int siteLogHistory, string homeDirectory, int createdByUserID) + [DnnDeprecated(7, 4, 0, "Please use CreatePortal overload with cultureCode", RemovalVersion = 10)] + public virtual partial int CreatePortal(string portalname, string currency, DateTime expiryDate, double hostFee, double hostSpace, int pageQuota, int userQuota, int siteLogHistory, string homeDirectory, int createdByUserID) { return this.CreatePortal( @@ -2210,7 +2211,7 @@ public virtual void ReplaceServerOnSchedules(string oldServername, string newSer { this.ExecuteNonQuery("ReplaceServerOnSchedules", oldServername, newServerName); } - + public virtual void ResetTermsAgreement(int portalId) { this.ExecuteNonQuery("ResetTermsAgreement", portalId); @@ -2302,26 +2303,26 @@ public virtual void UpdateUserRole(int userRoleId, int status, bool isOwner, Dat this.ExecuteNonQuery("UpdateUserRole", userRoleId, status, isOwner, this.GetNull(effectiveDate), this.GetNull(expiryDate), lastModifiedByUserID); } - [Obsolete("Support for users online was removed in 8.x, other solutions exist outside of the DNN Platform. Scheduled removal in v11.0.0.")] - public virtual void DeleteUsersOnline(int timeWindow) + [DnnDeprecated(8, 0, 0, "Other solutions exist outside of the DNN Platform", RemovalVersion = 11)] + public virtual partial void DeleteUsersOnline(int timeWindow) { this.ExecuteNonQuery("DeleteUsersOnline", timeWindow); } - [Obsolete("Support for users online was removed in 8.x, other solutions exist outside of the DNN Platform. Scheduled removal in v11.0.0.")] - public virtual IDataReader GetOnlineUser(int userId) + [DnnDeprecated(8, 0, 0, "Other solutions exist outside of the DNN Platform", RemovalVersion = 11)] + public virtual partial IDataReader GetOnlineUser(int userId) { return this.ExecuteReader("GetOnlineUser", userId); } - [Obsolete("Support for users online was removed in 8.x, other solutions exist outside of the DNN Platform. Scheduled removal in v11.0.0.")] - public virtual IDataReader GetOnlineUsers(int portalId) + [DnnDeprecated(8, 0, 0, "Other solutions exist outside of the DNN Platform", RemovalVersion = 11)] + public virtual partial IDataReader GetOnlineUsers(int portalId) { return this.ExecuteReader("GetOnlineUsers", portalId); } - [Obsolete("Support for users online was removed in 8.x, other solutions exist outside of the DNN Platform. Scheduled removal in v11.0.0.")] - public virtual void UpdateUsersOnline(Hashtable userList) + [DnnDeprecated(8, 0, 0, "Other solutions exist outside of the DNN Platform", RemovalVersion = 11)] + public virtual partial void UpdateUsersOnline(Hashtable userList) { if (userList.Count == 0) { @@ -3128,8 +3129,8 @@ public virtual void UpdateFolderMappingSetting(int folderMappingID, string setti lastModifiedByUserID); } - [Obsolete("Deprecated in Platform 9.2.0, please use the overload that takes passwordsRetained and daysRetained. Scheduled removal in v11.0.0.")] - public virtual IDataReader GetPasswordHistory(int userId) + [DnnDeprecated(9, 2, 0, "Please use the overload that takes passwordsRetained and daysRetained")] + public virtual partial IDataReader GetPasswordHistory(int userId) { return this.GetPasswordHistory(userId, int.MaxValue, int.MaxValue); } @@ -3139,8 +3140,8 @@ public virtual IDataReader GetPasswordHistory(int userId, int passwordsRetained, return this.ExecuteReader("GetPasswordHistory", this.GetNull(userId), passwordsRetained, daysRetained); } - [Obsolete("Deprecated in Platform 9.2.0, please use the overload that takes daysRetained. Scheduled removal in v11.0.0.")] - public virtual void AddPasswordHistory(int userId, string password, string passwordHistory, int retained) + [DnnDeprecated(9, 2, 0, "Please use the overload that takes daysRetained")] + public virtual partial void AddPasswordHistory(int userId, string password, string passwordHistory, int retained) { this.AddPasswordHistory(userId, password, passwordHistory, retained, int.MaxValue); } @@ -3646,8 +3647,8 @@ public virtual IDataReader GetIPFilters() /// The type of rule (1 for Allow, 2 for Deny). /// The ID of the acting user. /// The ID of the newly created IP Filter. - [Obsolete("Deprecated in v9.11.1. Use the overload that takes a notes string. Scheduled removal in v11.0.0.")] - public virtual int AddIPFilter(string ipAddress, string subnetMask, int ruleType, int createdByUserId) + [DnnDeprecated(9, 11, 1, "Use the overload that takes a notes string")] + public virtual partial int AddIPFilter(string ipAddress, string subnetMask, int ruleType, int createdByUserId) { return this.AddIPFilter(ipAddress, subnetMask, ruleType, createdByUserId, null); } @@ -3675,8 +3676,8 @@ public virtual void DeleteIPFilter(int ipFilterid) /// The IP mask to use for an IP range. /// The type of filter (1 to allow, 2 to deny). /// The ID of the acting user. - [Obsolete("Deprecated in v9.11.1. Use the overload that takes a notes string. Scheduled removal in v11.0.0.")] - public virtual void UpdateIPFilter(int ipFilterid, string ipAddress, string subnetMask, int ruleType, int lastModifiedByUserId) + [DnnDeprecated(9, 11, 1, "Use the overload that takes a notes string")] + public virtual partial void UpdateIPFilter(int ipFilterid, string ipAddress, string subnetMask, int ruleType, int lastModifiedByUserId) { this.UpdateIPFilter(ipFilterid, ipAddress, subnetMask, ruleType, lastModifiedByUserId, null); } @@ -3796,8 +3797,8 @@ public virtual int GetContentWorkflowStateUsageCount(int stateId) return this.ExecuteScalar("GetContentWorkflowStateUsageCount", stateId); } - [Obsolete("Deprecated in Platform 7.4.0. Scheduled removal in v10.0.0.")] - public virtual int AddContentWorkflow(int portalId, string workflowName, string description, bool isDeleted, bool startAfterCreating, bool startAfterEditing, bool dispositionEnabled) + [DnnDeprecated(7, 4, 0, "Use IWorkflowEngine", RemovalVersion = 10)] + public virtual partial int AddContentWorkflow(int portalId, string workflowName, string description, bool isDeleted, bool startAfterCreating, bool startAfterEditing, bool dispositionEnabled) { return this.ExecuteScalar( "AddContentWorkflow", @@ -3810,20 +3811,20 @@ public virtual int AddContentWorkflow(int portalId, string workflowName, string dispositionEnabled); } - [Obsolete("Deprecated in Platform 7.4.0. Scheduled removal in v10.0.0.")] - public virtual IDataReader GetContentWorkflow(int workflowId) + [DnnDeprecated(7, 4, 0, "Use IWorkflowEngine", RemovalVersion = 10)] + public virtual partial IDataReader GetContentWorkflow(int workflowId) { return this.ExecuteReader("GetContentWorkflow", workflowId); } - [Obsolete("Deprecated in Platform 7.4.0. Scheduled removal in v10.0.0.")] - public virtual IDataReader GetContentWorkflows(int portalId) + [DnnDeprecated(7, 4, 0, "Use IWorkflowEngine", RemovalVersion = 10)] + public virtual partial IDataReader GetContentWorkflows(int portalId) { return this.ExecuteReader("GetContentWorkflows", portalId); } - [Obsolete("Deprecated in Platform 7.4.0. Scheduled removal in v10.0.0.")] - public virtual void UpdateContentWorkflow(int workflowId, string workflowName, string description, bool isDeleted, bool startAfterCreating, bool startAfterEditing, bool dispositionEnabled) + [DnnDeprecated(7, 4, 0, "Use IWorkflowEngine", RemovalVersion = 10)] + public virtual partial void UpdateContentWorkflow(int workflowId, string workflowName, string description, bool isDeleted, bool startAfterCreating, bool startAfterEditing, bool dispositionEnabled) { this.ExecuteNonQuery( "UpdateContentWorkflow", @@ -3836,8 +3837,8 @@ public virtual void UpdateContentWorkflow(int workflowId, string workflowName, s dispositionEnabled); } - [Obsolete("Deprecated in Platform 7.4.0. Scheduled removal in v10.0.0.")] - public virtual int AddContentWorkflowState(int workflowId, string stateName, int order, bool isActive, bool sendEmail, bool sendMessage, bool isDisposalState, string onCompleteMessageSubject, string onCompleteMessageBody, string onDiscardMessageSubject, string onDiscardMessageBody) + [DnnDeprecated(7, 4, 0, "Use IWorkflowEngine", RemovalVersion = 10)] + public virtual partial int AddContentWorkflowState(int workflowId, string stateName, int order, bool isActive, bool sendEmail, bool sendMessage, bool isDisposalState, string onCompleteMessageSubject, string onCompleteMessageBody, string onDiscardMessageSubject, string onDiscardMessageBody) { return this.ExecuteScalar( "AddContentWorkflowState", @@ -3854,14 +3855,14 @@ public virtual int AddContentWorkflowState(int workflowId, string stateName, int onDiscardMessageBody); } - [Obsolete("Deprecated in Platform 7.4.0. Scheduled removal in v10.0.0.")] - public virtual void DeleteContentWorkflowState(int stateId) + [DnnDeprecated(7, 4, 0, "Use IWorkflowEngine", RemovalVersion = 10)] + public virtual partial void DeleteContentWorkflowState(int stateId) { this.ExecuteNonQuery("DeleteContentWorkflowState", stateId); } - [Obsolete("Deprecated in Platform 7.4.0. Scheduled removal in v10.0.0.")] - public virtual void UpdateContentWorkflowState(int stateId, string stateName, int order, bool isActive, bool sendEmail, bool sendMessage, bool isDisposalState, string onCompleteMessageSubject, string onCompleteMessageBody, string onDiscardMessageSubject, string onDiscardMessageBody) + [DnnDeprecated(7, 4, 0, "Use IWorkflowEngine", RemovalVersion = 10)] + public virtual partial void UpdateContentWorkflowState(int stateId, string stateName, int order, bool isActive, bool sendEmail, bool sendMessage, bool isDisposalState, string onCompleteMessageSubject, string onCompleteMessageBody, string onDiscardMessageSubject, string onDiscardMessageBody) { this.ExecuteNonQuery( "UpdateContentWorkflowState", @@ -3878,20 +3879,20 @@ public virtual void UpdateContentWorkflowState(int stateId, string stateName, in onDiscardMessageBody); } - [Obsolete("Deprecated in Platform 7.4.0. Scheduled removal in v10.0.0.")] - public virtual IDataReader GetContentWorkflowState(int stateId) + [DnnDeprecated(7, 4, 0, "Use IWorkflowEngine", RemovalVersion = 10)] + public virtual partial IDataReader GetContentWorkflowState(int stateId) { return this.ExecuteReader("GetContentWorkflowState", stateId); } - [Obsolete("Deprecated in Platform 7.4.0. Scheduled removal in v10.0.0.")] - public virtual IDataReader GetContentWorkflowStates(int workflowId) + [DnnDeprecated(7, 4, 0, "Use IWorkflowEngine", RemovalVersion = 10)] + public virtual partial IDataReader GetContentWorkflowStates(int workflowId) { return this.ExecuteReader("GetContentWorkflowStates", workflowId); } - [Obsolete("Deprecated in Platform 7.4.0. Use instead IWorkflowLogger.AddWorkflowLog. Scheduled removal in v10.0.0.")] - public virtual int AddContentWorkflowLog(string action, string comment, int user, int workflowId, int contentItemId) + [DnnDeprecated(7, 4, 0, "Use instead IWorkflowLogger.AddWorkflowLog", RemovalVersion = 10)] + public virtual partial int AddContentWorkflowLog(string action, string comment, int user, int workflowId, int contentItemId) { return this.ExecuteScalar( "AddContentWorkflowLog", @@ -3902,14 +3903,14 @@ public virtual int AddContentWorkflowLog(string action, string comment, int user contentItemId); } - [Obsolete("Deprecated in Platform 7.4.0. Use instead IWorkflowLogger.GetWorkflowLogs. Scheduled removal in v10.0.0.")] - public virtual IDataReader GetContentWorkflowLogs(int contentItemId, int workflowId) + [DnnDeprecated(7, 4, 0, "Use IWorkflowLogger.GetWorkflowLogs", RemovalVersion = 10)] + public virtual partial IDataReader GetContentWorkflowLogs(int contentItemId, int workflowId) { return this.ExecuteReader("GetContentWorkflowLogs", contentItemId, workflowId); } - [Obsolete("Deprecated in Platform 7.4.0. Scheduled removal in v10.0.0.")] - public virtual int DeleteContentWorkflowLogs(int contentItemId, int workflowId) + [DnnDeprecated(7, 4, 0, "Use IWorkflowEngine", RemovalVersion = 10)] + public virtual partial int DeleteContentWorkflowLogs(int contentItemId, int workflowId) { return this.ExecuteScalar("DeleteContentWorkflowLogs", contentItemId, workflowId); } @@ -3959,14 +3960,14 @@ public virtual IDataReader GetContentWorkflowStatePermissionsByStateID(int state return this.ExecuteReader("GetContentWorkflowStatePermissionsByStateID", stateId); } - [Obsolete("Deprecated in Platform 7.4.0. Scheduled removal in v10.0.0.")] - public virtual IDataReader GetContentWorkflowSource(int workflowId, string sourceName) + [DnnDeprecated(7, 4, 0, "Use IWorkflowEngine", RemovalVersion = 10)] + public virtual partial IDataReader GetContentWorkflowSource(int workflowId, string sourceName) { return this.ExecuteReader("GetContentWorkflowSource", workflowId, sourceName); } - [Obsolete("Deprecated in Platform 7.4.0. Scheduled removal in v10.0.0.")] - public virtual int AddContentWorkflowSource(int workflowId, string sourceName, string sourceType) + [DnnDeprecated(7, 4, 0, "Use IWorkflowEngine", RemovalVersion = 10)] + public virtual partial int AddContentWorkflowSource(int workflowId, string sourceName, string sourceType) { return this.ExecuteScalar("AddContentWorkflowSource", workflowId, sourceName, sourceType); } @@ -4143,8 +4144,8 @@ public virtual DataSet ExecuteDataSet(string procedureName, params object[] comm return Globals.ConvertDataReaderToDataSet(this.ExecuteReader(procedureName, commandParameters)); } - [Obsolete("Deprecated in 7.0.0. This method is unneccessary. Use the generic version ExecuteScalar.. Scheduled removal in v10.0.0.")] - public virtual object ExecuteScalar(string procedureName, params object[] commandParameters) + [DnnDeprecated(7, 0, 0, "0. This method is unnecessary. Use the generic version ExecuteScalar.", RemovalVersion = 10)] + public virtual partial object ExecuteScalar(string procedureName, params object[] commandParameters) { return this.ExecuteScalar(procedureName, commandParameters); } @@ -4173,11 +4174,13 @@ public virtual IDataReader ExecuteSQL(string sql, params IDataParameter[] comman } } - [Obsolete("Obsoleted in 9.3.0, please use GetFiles(int, bool, boo) instead. schedule to remove in 11.0.0.")] - public virtual IDataReader GetFiles(int folderId, bool retrieveUnpublishedFiles = false) + [DnnDeprecated(9, 3, 0, "Please use GetFiles(int, bool, bool) instead")] +#pragma warning disable CS1066 + public virtual partial IDataReader GetFiles(int folderId, bool retrieveUnpublishedFiles = false) { return this.GetFiles(folderId, retrieveUnpublishedFiles, false); } +#pragma warning restore CS1066 internal virtual IDictionary GetPortalSettingsBySetting(string settingName, string cultureCode) { diff --git a/DNN Platform/Library/DotNetNuke.Library.csproj b/DNN Platform/Library/DotNetNuke.Library.csproj index d3bc6401bf7..641837c2b71 100644 --- a/DNN Platform/Library/DotNetNuke.Library.csproj +++ b/DNN Platform/Library/DotNetNuke.Library.csproj @@ -51,7 +51,9 @@ TRACE;DEBUG AllRules.ruleset 1591, 3001, 3002, 1574, 1573 - 7 + latest + true + CS0618,CS0809,CS3005,CS3008,SA1600,SA1601,SA1602,SA1604,SA1605,SA1606,SA1608,SA1611,SA1612,SA1614 bin\ @@ -63,9 +65,9 @@ AllRules.ruleset 1591, 3001, 3002, 1574, 1573 true - - - 7 + latest + true + CS0618,CS0809,CS3005,CS3008,SA1600,SA1601,SA1602,SA1604,SA1605,SA1606,SA1608,SA1611,SA1612,SA1614 @@ -127,7 +129,7 @@ ..\..\packages\MimeKit.2.15.1\lib\net47\MimeKit.dll - ..\..\packages\Newtonsoft.Json.13.0.2\lib\net45\Newtonsoft.Json.dll + ..\..\packages\Newtonsoft.Json.13.0.3\lib\net45\Newtonsoft.Json.dll ..\..\packages\PetaPoco.Compiled.6.0.524\lib\net45\PetaPoco.dll @@ -749,6 +751,7 @@ + @@ -847,6 +850,11 @@ + + + + + @@ -1910,6 +1918,10 @@ + + {5fe5d021-9c8d-47a6-bd34-f328ba3e709c} + DotNetNuke.Internal.SourceGenerators + {ca056730-5759-41f8-a6c1-420f9c0c63e7} CountryListBox diff --git a/DNN Platform/Library/Entities/Content/ContentExtensions.cs b/DNN Platform/Library/Entities/Content/ContentExtensions.cs index 370143f5940..3cba1af9fb6 100644 --- a/DNN Platform/Library/Entities/Content/ContentExtensions.cs +++ b/DNN Platform/Library/Entities/Content/ContentExtensions.cs @@ -3,13 +3,13 @@ // See the LICENSE file in the project root for more information namespace DotNetNuke.Entities.Content { - using System; using System.Collections.Generic; using DotNetNuke.Entities.Content.Taxonomy; + using DotNetNuke.Internal.SourceGenerators; - [Obsolete("Moving ContentExtensions to the DotNetNuke.Entities.Content namespace was an error. Please use DotNetNuke.Entities.Content.Common.ContentExtensions. Scheduled removal in v10.0.0.")] - public static class ContentExtensions + [DnnDeprecated(7, 0, 0, "Moving ContentExtensions to the DotNetNuke.Entities.Content namespace was an error. Please use DotNetNuke.Entities.Content.Common.ContentExtensions.", RemovalVersion = 10)] + public static partial class ContentExtensions { // only forwarding public methods that existed as of 6.1.0 // calls to internal methods will be fixed in the source diff --git a/DNN Platform/Library/Entities/Content/IContentTypeController.cs b/DNN Platform/Library/Entities/Content/IContentTypeController.cs index 10a59aa8122..3138a9b0282 100644 --- a/DNN Platform/Library/Entities/Content/IContentTypeController.cs +++ b/DNN Platform/Library/Entities/Content/IContentTypeController.cs @@ -34,7 +34,7 @@ public interface IContentTypeController /// contentType.ContentType is empty. void UpdateContentType(ContentType contentType); - [Obsolete("Deprecated in DNN 8. ContentTypeController methods use DAL2 which manages the cache automagically. Scheduled removal in v11.0.0.")] + [Obsolete("Deprecated in DotNetNuke 8.0.0. ContentTypeController methods use DAL2 which manages the cache automagically. Scheduled removal in v11.0.0.")] void ClearContentTypeCache(); } } diff --git a/DNN Platform/Library/Entities/Content/Workflow/Obsolete/ContentWorkflow.cs b/DNN Platform/Library/Entities/Content/Workflow/Obsolete/ContentWorkflow.cs index 0932010e877..f944c65c8b8 100644 --- a/DNN Platform/Library/Entities/Content/Workflow/Obsolete/ContentWorkflow.cs +++ b/DNN Platform/Library/Entities/Content/Workflow/Obsolete/ContentWorkflow.cs @@ -7,12 +7,13 @@ namespace DotNetNuke.Entities.Content.Workflow // ReSharper enable CheckNamespace { - using System; - using System.Collections.Generic; - + using System.Collections.Generic; + + using DotNetNuke.Internal.SourceGenerators; + /// This entity represents a Workflow. - [Obsolete("Deprecated in Platform 7.4.0. Scheduled removal in v10.0.0.")] - public class ContentWorkflow + [DnnDeprecated(7, 4, 0, "Use IWorkflowEngine", RemovalVersion = 10)] + public partial class ContentWorkflow { /// Gets or sets workflow Id. public int WorkflowID { get; set; } diff --git a/DNN Platform/Library/Entities/Content/Workflow/Obsolete/ContentWorkflowController.cs b/DNN Platform/Library/Entities/Content/Workflow/Obsolete/ContentWorkflowController.cs index 52485a04a9d..7e022cee21e 100644 --- a/DNN Platform/Library/Entities/Content/Workflow/Obsolete/ContentWorkflowController.cs +++ b/DNN Platform/Library/Entities/Content/Workflow/Obsolete/ContentWorkflowController.cs @@ -16,6 +16,7 @@ namespace DotNetNuke.Entities.Content.Workflow using DotNetNuke.Data; using DotNetNuke.Entities.Portals; using DotNetNuke.Entities.Users; + using DotNetNuke.Internal.SourceGenerators; using DotNetNuke.Security; using DotNetNuke.Security.Permissions; using DotNetNuke.Security.Roles; @@ -23,8 +24,8 @@ namespace DotNetNuke.Entities.Content.Workflow using DotNetNuke.Services.Mail; using DotNetNuke.Services.Social.Notifications; - [Obsolete("Deprecated in Platform 7.4.0.. Scheduled removal in v10.0.0.")] - public class ContentWorkflowController : ComponentBase, IContentWorkflowController + [DnnDeprecated(7, 4, 0, "Use IWorkflowEngine", RemovalVersion = 10)] + public partial class ContentWorkflowController : ComponentBase, IContentWorkflowController { private const string ContentWorkflowNotificationType = "ContentWorkflowNotification"; private readonly ContentController contentController; @@ -35,7 +36,6 @@ private ContentWorkflowController() } /// - [Obsolete("Deprecated in Platform 7.4.0. Use instead IWorkflowEngine. Scheduled removal in v10.0.0.")] public void DiscardWorkflow(int contentItemId, string comment, int portalId, int userId) { var item = this.contentController.GetContentItem(contentItemId); @@ -47,7 +47,6 @@ public void DiscardWorkflow(int contentItemId, string comment, int portalId, int } /// - [Obsolete("Deprecated in Platform 7.4.0. Use instead IWorkflowEngine. Scheduled removal in v10.0.0.")] public void CompleteWorkflow(int contentItemId, string comment, int portalId, int userId) { var item = this.contentController.GetContentItem(contentItemId); @@ -59,7 +58,6 @@ public void CompleteWorkflow(int contentItemId, string comment, int portalId, in } /// - [Obsolete("Deprecated in Platform 7.4.0. Scheduled removal in v10.0.0.")] public string ReplaceNotificationTokens(string text, ContentWorkflow workflow, ContentItem item, ContentWorkflowState state, int portalID, int userID, string comment = "") { var user = UserController.GetUserById(portalID, userID); @@ -75,14 +73,12 @@ public string ReplaceNotificationTokens(string text, ContentWorkflow workflow, C } /// - [Obsolete("Deprecated in Platform 7.4.0. Scheduled removal in v10.0.0.")] public void CompleteState(int itemID, string subject, string body, string comment, int portalID, int userID) { this.CompleteState(itemID, subject, body, comment, portalID, userID, string.Empty); } /// - [Obsolete("Deprecated in Platform 7.4.0. Use instead IWorkflowEngine. Scheduled removal in v10.0.0.")] public void StartWorkflow(int workflowID, int itemID, int userID) { var item = this.contentController.GetContentItem(itemID); @@ -108,7 +104,6 @@ public void StartWorkflow(int workflowID, int itemID, int userID) } /// - [Obsolete("Deprecated in Platform 7.4.0. Use instead IWorkflowEngine. Scheduled removal in v10.0.0.")] public void CompleteState(int itemID, string subject, string body, string comment, int portalID, int userID, string source, params string[] parameters) { var item = this.contentController.GetContentItem(itemID); @@ -144,7 +139,6 @@ public void CompleteState(int itemID, string subject, string body, string commen } /// - [Obsolete("Deprecated in Platform 7.4.0. Use instead IWorkflowEngine. Scheduled removal in v10.0.0.")] public void DiscardState(int itemID, string subject, string body, string comment, int portalID, int userID) { var item = this.contentController.GetContentItem(itemID); @@ -171,7 +165,6 @@ public void DiscardState(int itemID, string subject, string body, string comment } /// - [Obsolete("Deprecated in Platform 7.4.0. Use instead IWorkflowEngine. Scheduled removal in v10.0.0.")] public bool IsWorkflowCompleted(int itemID) { var item = this.contentController.GetContentItem(itemID); // Ensure DB values @@ -185,7 +178,6 @@ public bool IsWorkflowCompleted(int itemID) } /// - [Obsolete("Deprecated in Platform 7.4.0. Use instead IWorkflowEngine. Scheduled removal in v10.0.0.")] public bool IsWorkflowOnDraft(int itemID) { var item = this.contentController.GetContentItem(itemID); // Ensure DB values @@ -199,7 +191,6 @@ public bool IsWorkflowOnDraft(int itemID) } /// - [Obsolete("Deprecated in Platform 7.4.0. Use instead IWorkflowLogger. Scheduled removal in v10.0.0.")] public void AddWorkflowLog(ContentItem item, string action, string comment, int userID) { var workflow = this.GetWorkflow(item); @@ -208,28 +199,24 @@ public void AddWorkflowLog(ContentItem item, string action, string comment, int } /// - [Obsolete("Deprecated in Platform 7.4.0. Use instead IWorkflowLogger. Scheduled removal in v10.0.0.")] public IEnumerable GetWorkflowLogs(int contentItemId, int workflowId) { return CBO.FillCollection(DataProvider.Instance().GetContentWorkflowLogs(contentItemId, workflowId)); } /// - [Obsolete("Deprecated in Platform 7.4.0.. Scheduled removal in v10.0.0.")] public void DeleteWorkflowLogs(int contentItemID, int workflowID) { DataProvider.Instance().DeleteContentWorkflowLogs(contentItemID, workflowID); } /// - [Obsolete("Deprecated in Platform 7.4.0. Use instead IWorkflowStateManager. Scheduled removal in v10.0.0.")] public IEnumerable GetWorkflowStatePermissionByState(int stateID) { return CBO.FillCollection(DataProvider.Instance().GetContentWorkflowStatePermissionsByStateID(stateID)); } /// - [Obsolete("Deprecated in Platform 7.4.0. Use instead IWorkflowStateManager. Scheduled removal in v10.0.0.")] public void AddWorkflowStatePermission(ContentWorkflowStatePermission permission, int lastModifiedByUserID) { DataProvider.Instance().AddContentWorkflowStatePermission( @@ -242,7 +229,6 @@ public void AddWorkflowStatePermission(ContentWorkflowStatePermission permission } /// - [Obsolete("Deprecated in Platform 7.4.0. Use instead IWorkflowStateManager. Scheduled removal in v10.0.0.")] public void UpdateWorkflowStatePermission(ContentWorkflowStatePermission permission, int lastModifiedByUserID) { DataProvider.Instance().UpdateContentWorkflowStatePermission( @@ -256,21 +242,18 @@ public void UpdateWorkflowStatePermission(ContentWorkflowStatePermission permiss } /// - [Obsolete("Deprecated in Platform 7.4.0. Use instead IWorkflowStateManager. Scheduled removal in v10.0.0.")] public void DeleteWorkflowStatePermission(int workflowStatePermissionID) { DataProvider.Instance().DeleteContentWorkflowStatePermission(workflowStatePermissionID); } /// - [Obsolete("Deprecated in Platform 7.4.0. Use instead IWorkflowStateManager. Scheduled removal in v10.0.0.")] public ContentWorkflowState GetWorkflowStateByID(int stateID) { return CBO.FillObject(DataProvider.Instance().GetContentWorkflowState(stateID)); } /// - [Obsolete("Deprecated in Platform 7.4.0. Use instead IWorkflowStateManager. Scheduled removal in v10.0.0.")] public void AddWorkflowState(ContentWorkflowState state) { var id = DataProvider.Instance().AddContentWorkflowState( @@ -289,7 +272,6 @@ public void AddWorkflowState(ContentWorkflowState state) } /// - [Obsolete("Deprecated in Platform 7.4.0. Use instead IWorkflowStateManager. Scheduled removal in v10.0.0.")] public void UpdateWorkflowState(ContentWorkflowState state) { DataProvider.Instance().UpdateContentWorkflowState( @@ -307,21 +289,18 @@ public void UpdateWorkflowState(ContentWorkflowState state) } /// - [Obsolete("Deprecated in Platform 7.4.0. Use instead IWorkflowStateManager. Scheduled removal in v10.0.0.")] public IEnumerable GetWorkflowStates(int workflowID) { return CBO.FillCollection(DataProvider.Instance().GetContentWorkflowStates(workflowID)); } /// - [Obsolete("Deprecated in Platform 7.4.0. Use instead IWorkflowManager. Scheduled removal in v10.0.0.")] public IEnumerable GetWorkflows(int portalID) { return CBO.FillCollection(DataProvider.Instance().GetContentWorkflows(portalID)); } /// - [Obsolete("Deprecated in Platform 7.4.0. Use instead IWorkflowManager. Scheduled removal in v10.0.0.")] public ContentWorkflow GetWorkflow(ContentItem item) { var state = this.GetWorkflowStateByID(item.StateID); @@ -334,7 +313,6 @@ public ContentWorkflow GetWorkflow(ContentItem item) } /// - [Obsolete("Deprecated in Platform 7.4.0. Use instead IWorkflowManager. Scheduled removal in v10.0.0.")] public void AddWorkflow(ContentWorkflow workflow) { var id = DataProvider.Instance().AddContentWorkflow(workflow.PortalID, workflow.WorkflowName, workflow.Description, workflow.IsDeleted, workflow.StartAfterCreating, workflow.StartAfterEditing, workflow.DispositionEnabled); @@ -342,14 +320,12 @@ public void AddWorkflow(ContentWorkflow workflow) } /// - [Obsolete("Deprecated in Platform 7.4.0. Use instead IWorkflowManager. Scheduled removal in v10.0.0.")] public void UpdateWorkflow(ContentWorkflow workflow) { DataProvider.Instance().UpdateContentWorkflow(workflow.WorkflowID, workflow.WorkflowName, workflow.Description, workflow.IsDeleted, workflow.StartAfterCreating, workflow.StartAfterEditing, workflow.DispositionEnabled); } /// - [Obsolete("Deprecated in Platform 7.4.0. Use instead IWorkflowManager. Scheduled removal in v10.0.0.")] public ContentWorkflow GetWorkflowByID(int workflowID) { var workflow = CBO.FillObject(DataProvider.Instance().GetContentWorkflow(workflowID)); @@ -363,7 +339,6 @@ public ContentWorkflow GetWorkflowByID(int workflowID) } /// - [Obsolete("Deprecated in Platform 7.4.0. Use instead ISystemWorkflowManager. Scheduled removal in v10.0.0.")] public void CreateDefaultWorkflows(int portalId) { if (this.GetWorkflows(portalId).Any(w => w.WorkflowName == Localization.GetString("DefaultWorkflowName"))) @@ -460,7 +435,6 @@ public void CreateDefaultWorkflows(int portalId) } /// - [Obsolete("Deprecated in Platform 7.4.0. Use instead ISystemWorkflowManager. Scheduled removal in v10.0.0.")] public ContentWorkflow GetDefaultWorkflow(int portalID) { var wf = this.GetWorkflows(portalID).First(); // We assume there is only 1 Workflow. This needs to be changed for other scenarios @@ -469,7 +443,6 @@ public ContentWorkflow GetDefaultWorkflow(int portalID) } /// - [Obsolete("Deprecated in Platform 7.4.0. Use instead IWorkflowSecurity. Scheduled removal in v10.0.0.")] public bool IsAnyReviewer(int workflowID) { var workflow = this.GetWorkflowByID(workflowID); @@ -477,7 +450,6 @@ public bool IsAnyReviewer(int workflowID) } /// - [Obsolete("Deprecated in Platform 7.4.0. Use instead IWorkflowSecurity. Scheduled removal in v10.0.0.")] public bool IsAnyReviewer(int portalID, int userID, int workflowID) { var workflow = this.GetWorkflowByID(workflowID); @@ -485,7 +457,6 @@ public bool IsAnyReviewer(int portalID, int userID, int workflowID) } /// - [Obsolete("Deprecated in Platform 7.4.0. Use instead IWorkflowSecurity. Scheduled removal in v10.0.0.")] public bool IsReviewer(int stateID) { var permissions = this.GetWorkflowStatePermissionByState(stateID); @@ -494,7 +465,6 @@ public bool IsReviewer(int stateID) } /// - [Obsolete("Deprecated in Platform 7.4.0. Use instead IWorkflowSecurity. Scheduled removal in v10.0.0.")] public bool IsReviewer(int portalID, int userID, int stateID) { var permissions = this.GetWorkflowStatePermissionByState(stateID); @@ -505,7 +475,6 @@ public bool IsReviewer(int portalID, int userID, int stateID) } /// - [Obsolete("Deprecated in Platform 7.4.0. Use instead IWorkflowSecurity. Scheduled removal in v10.0.0.")] public bool IsCurrentReviewer(int portalID, int userID, int itemID) { var item = this.contentController.GetContentItem(itemID); @@ -513,7 +482,6 @@ public bool IsCurrentReviewer(int portalID, int userID, int itemID) } /// - [Obsolete("Deprecated in Platform 7.4.0. Use instead IWorkflowSecurity. Scheduled removal in v10.0.0.")] public bool IsCurrentReviewer(int itemID) { var item = this.contentController.GetContentItem(itemID); @@ -521,14 +489,12 @@ public bool IsCurrentReviewer(int itemID) } /// - [Obsolete("Deprecated in Platform 7.4.0. Scheduled removal in v10.0.0.")] public ContentWorkflowSource GetWorkflowSource(int workflowId, string sourceName) { return CBO.FillObject(DataProvider.Instance().GetContentWorkflowSource(workflowId, sourceName)); } /// - [Obsolete("Deprecated in Platform 7.4.0. Scheduled removal in v10.0.0.")] public void SendWorkflowNotification(bool sendEmail, bool sendMessage, PortalSettings settings, IEnumerable roles, IEnumerable users, string subject, string body, string comment, int userID) { var replacedSubject = this.ReplaceNotificationTokens(subject, null, null, null, settings.PortalId, userID); diff --git a/DNN Platform/Library/Entities/Content/Workflow/Obsolete/ContentWorkflowLog.cs b/DNN Platform/Library/Entities/Content/Workflow/Obsolete/ContentWorkflowLog.cs index eb87d8d324c..715053223eb 100644 --- a/DNN Platform/Library/Entities/Content/Workflow/Obsolete/ContentWorkflowLog.cs +++ b/DNN Platform/Library/Entities/Content/Workflow/Obsolete/ContentWorkflowLog.cs @@ -7,11 +7,13 @@ namespace DotNetNuke.Entities.Content.Workflow // ReSharper enable CheckNamespace { - using System; + using System; + + using DotNetNuke.Internal.SourceGenerators; /// This entity represents a Workflow Log. - [Obsolete("Deprecated in Platform 7.4.0. Scheduled removal in v10.0.0.")] - public class ContentWorkflowLog + [DnnDeprecated(7, 4, 0, "Use IWorkflowEngine", RemovalVersion = 10)] + public partial class ContentWorkflowLog { /// Gets or sets workflow log Id. public int WorkflowLogID { get; set; } diff --git a/DNN Platform/Library/Entities/Content/Workflow/Obsolete/ContentWorkflowLogType.cs b/DNN Platform/Library/Entities/Content/Workflow/Obsolete/ContentWorkflowLogType.cs index e949b1be81f..4f1a7a37f45 100644 --- a/DNN Platform/Library/Entities/Content/Workflow/Obsolete/ContentWorkflowLogType.cs +++ b/DNN Platform/Library/Entities/Content/Workflow/Obsolete/ContentWorkflowLogType.cs @@ -10,7 +10,7 @@ namespace DotNetNuke.Entities.Content.Workflow using System; /// This enum represents the possible list of WorkflowLogType. - [Obsolete("Deprecated in Platform 7.4.0. Scheduled removal in v10.0.0.")] + [Obsolete("Deprecated in DotNetNuke 7.4.0. Use IWorkflowEngine. Scheduled removal in v10.0.0.")] public enum ContentWorkflowLogType { WorkflowStarted = 0, diff --git a/DNN Platform/Library/Entities/Content/Workflow/Obsolete/ContentWorkflowSource.cs b/DNN Platform/Library/Entities/Content/Workflow/Obsolete/ContentWorkflowSource.cs index d985c7ed9fa..503dc8ff85a 100644 --- a/DNN Platform/Library/Entities/Content/Workflow/Obsolete/ContentWorkflowSource.cs +++ b/DNN Platform/Library/Entities/Content/Workflow/Obsolete/ContentWorkflowSource.cs @@ -7,10 +7,10 @@ namespace DotNetNuke.Entities.Content.Workflow // ReSharper enable CheckNamespace { - using System; - - [Obsolete("Deprecated in Platform 7.4.0.. Scheduled removal in v10.0.0.")] - public class ContentWorkflowSource + using DotNetNuke.Internal.SourceGenerators; + + [DnnDeprecated(7, 4, 0, "Use IWorkflowEngine", RemovalVersion = 10)] + public partial class ContentWorkflowSource { public int WorkflowId { get; set; } diff --git a/DNN Platform/Library/Entities/Content/Workflow/Obsolete/ContentWorkflowState.cs b/DNN Platform/Library/Entities/Content/Workflow/Obsolete/ContentWorkflowState.cs index e1208f88389..f94043b5b40 100644 --- a/DNN Platform/Library/Entities/Content/Workflow/Obsolete/ContentWorkflowState.cs +++ b/DNN Platform/Library/Entities/Content/Workflow/Obsolete/ContentWorkflowState.cs @@ -7,11 +7,11 @@ namespace DotNetNuke.Entities.Content.Workflow // ReSharper enable CheckNamespace { - using System; - + using DotNetNuke.Internal.SourceGenerators; + /// This entity represents a Workflow State. - [Obsolete("Deprecated in Platform 7.4.0. Scheduled removal in v10.0.0.")] - public class ContentWorkflowState + [DnnDeprecated(7, 4, 0, "Use IWorkflowEngine", RemovalVersion = 10)] + public partial class ContentWorkflowState { /// Gets or sets state Id. public int StateID { get; set; } diff --git a/DNN Platform/Library/Entities/Content/Workflow/Obsolete/ContentWorkflowStatePermission.cs b/DNN Platform/Library/Entities/Content/Workflow/Obsolete/ContentWorkflowStatePermission.cs index 98f23b35845..ae77ed7b078 100644 --- a/DNN Platform/Library/Entities/Content/Workflow/Obsolete/ContentWorkflowStatePermission.cs +++ b/DNN Platform/Library/Entities/Content/Workflow/Obsolete/ContentWorkflowStatePermission.cs @@ -7,13 +7,12 @@ namespace DotNetNuke.Entities.Content.Workflow // ReSharper enable CheckNamespace { - using System; - + using DotNetNuke.Internal.SourceGenerators; using DotNetNuke.Security.Permissions; /// This entity represents a state permission. - [Obsolete("Deprecated in Platform 7.4.0.. Scheduled removal in v10.0.0.")] - public class ContentWorkflowStatePermission : PermissionInfoBase + [DnnDeprecated(7, 4, 0, "Use IWorkflowEngine", RemovalVersion = 10)] + public partial class ContentWorkflowStatePermission : PermissionInfoBase { /// Gets or sets workflow state permission Id. public int WorkflowStatePermissionID { get; set; } diff --git a/DNN Platform/Library/Entities/Content/Workflow/Obsolete/IContentWorkflowAction.cs b/DNN Platform/Library/Entities/Content/Workflow/Obsolete/IContentWorkflowAction.cs index 2ed66a109c9..c1bcf402f45 100644 --- a/DNN Platform/Library/Entities/Content/Workflow/Obsolete/IContentWorkflowAction.cs +++ b/DNN Platform/Library/Entities/Content/Workflow/Obsolete/IContentWorkflowAction.cs @@ -7,10 +7,10 @@ namespace DotNetNuke.Entities.Content.Workflow // ReSharper enable CheckNamespace { - using System; - - [Obsolete("Deprecated in Platform 7.4.0.. Scheduled removal in v10.0.0.")] - public interface IContentWorkflowAction + using DotNetNuke.Internal.SourceGenerators; + + [DnnDeprecated(7, 4, 0, "Use IWorkflowEngine", RemovalVersion = 10)] + public partial interface IContentWorkflowAction { string GetAction(string[] parameters); } diff --git a/DNN Platform/Library/Entities/Content/Workflow/Obsolete/IContentWorkflowController.cs b/DNN Platform/Library/Entities/Content/Workflow/Obsolete/IContentWorkflowController.cs index 85daa47c197..1608cfdfa2e 100644 --- a/DNN Platform/Library/Entities/Content/Workflow/Obsolete/IContentWorkflowController.cs +++ b/DNN Platform/Library/Entities/Content/Workflow/Obsolete/IContentWorkflowController.cs @@ -7,119 +7,84 @@ namespace DotNetNuke.Entities.Content.Workflow // ReSharper enable CheckNamespace { - using System; using System.Collections.Generic; using DotNetNuke.Entities.Portals; using DotNetNuke.Entities.Users; + using DotNetNuke.Internal.SourceGenerators; using DotNetNuke.Security.Roles; - [Obsolete("Deprecated in Platform 7.4.0.. Scheduled removal in v10.0.0.")] - public interface IContentWorkflowController + [DnnDeprecated(7, 4, 0, "Use IWorkflowEngine", RemovalVersion = 10)] + public partial interface IContentWorkflowController { - [Obsolete("Deprecated in Platform 7.4.0. Use instead IWorkflowEngine. Scheduled removal in v10.0.0.")] void StartWorkflow(int workflowID, int itemID, int userID); - [Obsolete("Deprecated in Platform 7.4.0. Use instead IWorkflowEngine. Scheduled removal in v10.0.0.")] void CompleteState(int itemID, string subject, string body, string comment, int portalID, int userID); - [Obsolete("Deprecated in Platform 7.4.0. Use instead IWorkflowEngine. Scheduled removal in v10.0.0.")] void CompleteState(int itemID, string subject, string body, string comment, int portalID, int userID, string source, params string[] parameters); - [Obsolete("Deprecated in Platform 7.4.0. Use instead IWorkflowEngine. Scheduled removal in v10.0.0.")] void DiscardState(int itemID, string subject, string body, string comment, int portalID, int userID); - [Obsolete("Deprecated in Platform 7.4.0. Use instead IWorkflowEngine. Scheduled removal in v10.0.0.")] bool IsWorkflowCompleted(int itemID); - [Obsolete("Deprecated in Platform 7.4.0. Use instead IWorkflowEngine. Scheduled removal in v10.0.0.")] bool IsWorkflowOnDraft(int itemID); - [Obsolete("Deprecated in Platform 7.4.0.. Scheduled removal in v10.0.0.")] void SendWorkflowNotification(bool sendEmail, bool sendMessage, PortalSettings settings, IEnumerable roles, IEnumerable users, string subject, string body, string comment, int userID); - [Obsolete("Deprecated in Platform 7.4.0. Use instead IWorkflowEngine. Scheduled removal in v10.0.0.")] void DiscardWorkflow(int contentItemId, string comment, int portalId, int userId); - [Obsolete("Deprecated in Platform 7.4.0. Use instead IWorkflowEngine. Scheduled removal in v10.0.0.")] void CompleteWorkflow(int contentItemId, string comment, int portalId, int userId); - [Obsolete("Deprecated in Platform 7.4.0. Scheduled removal in v10.0.0.")] string ReplaceNotificationTokens(string text, ContentWorkflow workflow, ContentItem item, ContentWorkflowState state, int portalID, int userID, string comment = ""); - [Obsolete("Deprecated in Platform 7.4.0.. Scheduled removal in v10.0.0.")] ContentWorkflowSource GetWorkflowSource(int workflowId, string sourceName); - [Obsolete("Deprecated in Platform 7.4.0. Use instead IWorkflowManager. Scheduled removal in v10.0.0.")] IEnumerable GetWorkflows(int portalID); - [Obsolete("Deprecated in Platform 7.4.0. Use instead ISystemWorkflowManager. Scheduled removal in v10.0.0.")] ContentWorkflow GetDefaultWorkflow(int portalID); - [Obsolete("Deprecated in Platform 7.4.0. Use instead IWorkflowManager. Scheduled removal in v10.0.0.")] ContentWorkflow GetWorkflowByID(int workflowID); - [Obsolete("Deprecated in Platform 7.4.0. Use instead IWorkflowManager. Scheduled removal in v10.0.0.")] ContentWorkflow GetWorkflow(ContentItem item); - [Obsolete("Deprecated in Platform 7.4.0. Use instead IWorkflowManager. Scheduled removal in v10.0.0.")] void AddWorkflow(ContentWorkflow workflow); - [Obsolete("Deprecated in Platform 7.4.0. Use instead IWorkflowManager. Scheduled removal in v10.0.0.")] void UpdateWorkflow(ContentWorkflow workflow); - [Obsolete("Deprecated in Platform 7.4.0. Use instead IWorkflowLogger. Scheduled removal in v10.0.0.")] IEnumerable GetWorkflowLogs(int workflowId, int contentItemId); - [Obsolete("Deprecated in Platform 7.4.0.. Scheduled removal in v10.0.0.")] void DeleteWorkflowLogs(int workflowID, int contentItemID); - [Obsolete("Deprecated in Platform 7.4.0. Use instead IWorkflowStateManager. Scheduled removal in v10.0.0.")] IEnumerable GetWorkflowStates(int workflowID); - [Obsolete("Deprecated in Platform 7.4.0. Use instead IWorkflowStateManager. Scheduled removal in v10.0.0.")] ContentWorkflowState GetWorkflowStateByID(int stateID); - [Obsolete("Deprecated in Platform 7.4.0. Use instead IWorkflowStateManager. Scheduled removal in v10.0.0.")] void AddWorkflowState(ContentWorkflowState state); - [Obsolete("Deprecated in Platform 7.4.0. Use instead IWorkflowStateManager. Scheduled removal in v10.0.0.")] void UpdateWorkflowState(ContentWorkflowState state); - [Obsolete("Deprecated in Platform 7.4.0. Use instead IWorkflowStateManager. Scheduled removal in v10.0.0.")] IEnumerable GetWorkflowStatePermissionByState(int stateID); - [Obsolete("Deprecated in Platform 7.4.0. Use instead IWorkflowStateManager. Scheduled removal in v10.0.0.")] void AddWorkflowStatePermission(ContentWorkflowStatePermission permission, int lastModifiedByUserID); - [Obsolete("Deprecated in Platform 7.4.0. Use instead IWorkflowStateManager. Scheduled removal in v10.0.0.")] void UpdateWorkflowStatePermission(ContentWorkflowStatePermission permission, int lasModifiedByUserId); - [Obsolete("Deprecated in Platform 7.4.0. Use instead IWorkflowStateManager. Scheduled removal in v10.0.0.")] void DeleteWorkflowStatePermission(int workflowStatePermissionID); - [Obsolete("Deprecated in Platform 7.4.0. Use instead IWorkflowSecurity. Scheduled removal in v10.0.0.")] bool IsAnyReviewer(int portalID, int userID, int workflowID); - [Obsolete("Deprecated in Platform 7.4.0. Use instead IWorkflowSecurity. Scheduled removal in v10.0.0.")] bool IsAnyReviewer(int workflowID); - [Obsolete("Deprecated in Platform 7.4.0. Use instead IWorkflowSecurity. Scheduled removal in v10.0.0.")] bool IsCurrentReviewer(int portalId, int userID, int itemID); - [Obsolete("Deprecated in Platform 7.4.0. Use instead IWorkflowSecurity. Scheduled removal in v10.0.0.")] bool IsCurrentReviewer(int itemID); - [Obsolete("Deprecated in Platform 7.4.0. Use instead IWorkflowSecurity. Scheduled removal in v10.0.0.")] bool IsReviewer(int portalId, int userID, int stateID); - [Obsolete("Deprecated in Platform 7.4.0. Use instead IWorkflowSecurity. Scheduled removal in v10.0.0.")] bool IsReviewer(int stateID); - [Obsolete("Deprecated in Platform 7.4.0. Use instead IWorkflowLogger. Scheduled removal in v10.0.0.")] void AddWorkflowLog(ContentItem item, string action, string comment, int userID); - [Obsolete("Deprecated in Platform 7.4.0. Use instead ISystemWorkflowManager. Scheduled removal in v10.0.0.")] void CreateDefaultWorkflows(int portalId); } } diff --git a/DNN Platform/Library/Entities/Controllers/IHostController.cs b/DNN Platform/Library/Entities/Controllers/IHostController.cs index e5d36aa61d1..9145e6c85a7 100644 --- a/DNN Platform/Library/Entities/Controllers/IHostController.cs +++ b/DNN Platform/Library/Entities/Controllers/IHostController.cs @@ -4,9 +4,10 @@ namespace DotNetNuke.Entities.Controllers { - using System; using System.Collections.Generic; + using DotNetNuke.Internal.SourceGenerators; + /// Interface of HostController. /// /// @@ -20,117 +21,99 @@ namespace DotNetNuke.Entities.Controllers /// /// /// - [Obsolete("Deprecated in 9.7.1. Scheduled for removal in v11.0.0, use DotNetNuke.Abstractions.Application.IHostSettingsService instead.")] - public interface IHostController + [DnnDeprecated(9, 7, 1, "use DotNetNuke.Abstractions.Application.IHostSettingsService instead")] + public partial interface IHostController { /// Gets the setting value for the specific key. /// The setting key string. /// host setting as a boolean. - [Obsolete("Deprecated in 9.7.1. Scheduled for removal in v11.0.0, use DotNetNuke.Abstractions.Application.IHostSettingsService instead.")] bool GetBoolean(string key); /// Gets the setting value for the specific key. /// The setting key string. /// Default value returned if the setting is not found or not compatible with the requested type. /// host setting or the provided default value as a . - [Obsolete("Deprecated in 9.7.1. Scheduled for removal in v11.0.0, use DotNetNuke.Abstractions.Application.IHostSettingsService instead.")] bool GetBoolean(string key, bool defaultValue); /// Gets the setting value for the specific key. /// The setting key string. /// Default value returned if the setting is not found or not compatible with the requested type. /// Host setting or the provided default value as a . - [Obsolete("Deprecated in 9.7.1. Scheduled for removal in v11.0.0, use DotNetNuke.Abstractions.Application.IHostSettingsService instead.")] double GetDouble(string key, double defaultValue); /// Gets the setting value for the specific key. /// The setting key string. /// Host setting as a . - [Obsolete("Deprecated in 9.7.1. Scheduled for removal in v11.0.0, use DotNetNuke.Abstractions.Application.IHostSettingsService instead.")] double GetDouble(string key); /// Gets the setting value for the specific key. /// The setting key string. /// Host setting as an . - [Obsolete("Deprecated in 9.7.1. Scheduled for removal in v11.0.0, use DotNetNuke.Abstractions.Application.IHostSettingsService instead.")] int GetInteger(string key); /// Gets the setting value for the specific key. /// The setting key string. /// Default value returned if the setting is not found or not compatible with the requested type. /// Host setting or provided default value as a . - [Obsolete("Deprecated in 9.7.1. Scheduled for removal in v11.0.0, use DotNetNuke.Abstractions.Application.IHostSettingsService instead.")] int GetInteger(string key, int defaultValue); /// Gets the host settings. /// Host settings as a . - [Obsolete("Deprecated in 9.7.1. Scheduled for removal in v11.0.0, use DotNetNuke.Abstractions.Application.IHostSettingsService instead.")] Dictionary GetSettings(); /// Gets the host settings. /// Host settings as a . - [Obsolete("Deprecated in 9.7.1. Scheduled for removal in v11.0.0, use DotNetNuke.Abstractions.Application.IHostSettingsService instead.")] Dictionary GetSettingsDictionary(); /// Gets an encrypted host setting as a . /// The setting key string. /// The passPhrase used to decrypt the setting value. /// The setting value as a . - [Obsolete("Deprecated in 9.7.1. Scheduled for removal in v11.0.0, use DotNetNuke.Abstractions.Application.IHostSettingsService instead.")] string GetEncryptedString(string key, string passPhrase); /// Gets the setting value for a specific key. /// The setting key string. /// The setting value as a . - [Obsolete("Deprecated in 9.7.1. Scheduled for removal in v11.0.0, use DotNetNuke.Abstractions.Application.IHostSettingsService instead.")] string GetString(string key); /// Gets the setting value for a specific key. /// The seeting key string. /// /// Default value returned if the setting is not found. - [Obsolete("Deprecated in 9.7.1. Scheduled for removal in v11.0.0, use DotNetNuke.Abstractions.Application.IHostSettingsService instead.")] string GetString(string key, string defaultValue); /// Updates the specified settings. /// The settings to update. - [Obsolete("Deprecated in 9.7.1. Scheduled for removal in v11.0.0, use DotNetNuke.Abstractions.Application.IHostSettingsService instead.")] void Update(Dictionary settings); /// Updates the specified config. /// The configuration setting. - [Obsolete("Deprecated in 9.7.1. Scheduled for removal in v11.0.0, use DotNetNuke.Abstractions.Application.IHostSettingsService instead.")] void Update(ConfigurationSetting config); /// Updates the specified config, ontionally clearing the cache. /// The configuaration setting. /// If set to true, will clear the cache after updating the setting. - [Obsolete("Deprecated in 9.7.1. Scheduled for removal in v11.0.0, use DotNetNuke.Abstractions.Application.IHostSettingsService instead.")] void Update(ConfigurationSetting config, bool clearCache); /// Updates the setting for a specific key. /// The setting key string. /// The value to update. /// If set to true, will clear the cache after updating the setting. - [Obsolete("Deprecated in 9.7.1. Scheduled for removal in v11.0.0, use DotNetNuke.Abstractions.Application.IHostSettingsService instead.")] void Update(string key, string value, bool clearCache); /// Updates the setting for a specific key. /// The setting key string. /// The value to update. - [Obsolete("Deprecated in 9.7.1. Scheduled for removal in v11.0.0, use DotNetNuke.Abstractions.Application.IHostSettingsService instead.")] void Update(string key, string value); /// Takes in a value, encrypts it with a FIPS compliant algorithm and stores. /// host settings key. /// host settings value. /// pass phrase to allow encryption/decryption. - [Obsolete("Deprecated in 9.7.1. Scheduled for removal in v11.0.0, use DotNetNuke.Abstractions.Application.IHostSettingsService instead.")] void UpdateEncryptedString(string key, string value, string passPhrase); /// Increments the Client Resource Manager (CRM) version to bust local cache. /// If true also forces a CRM version increment on portals that have non-default settings for CRM. - [Obsolete("Deprecated in 9.7.1. Scheduled for removal in v11.0.0, use DotNetNuke.Abstractions.Application.IHostSettingsService instead.")] void IncrementCrmVersion(bool includeOverridingPortals); } } diff --git a/DNN Platform/Library/Entities/EventManager.cs b/DNN Platform/Library/Entities/EventManager.cs index c404fd0a0ea..45b5c8cc58d 100644 --- a/DNN Platform/Library/Entities/EventManager.cs +++ b/DNN Platform/Library/Entities/EventManager.cs @@ -26,7 +26,7 @@ public class EventManager : ServiceLocator, IEventM private readonly IEventLogger eventLogger; /// Initializes a new instance of the class. - [Obsolete("Deprecated in 9.8.1, use overload taking IEventLogger. Scheduled removal in v11.0.0.")] + [Obsolete("Deprecated in DotNetNuke 9.8.1. Use overload taking IEventLogger. Scheduled removal in v11.0.0.")] public EventManager() : this(null) { diff --git a/DNN Platform/Library/Entities/Host/Host.cs b/DNN Platform/Library/Entities/Host/Host.cs index d1d619741eb..3cf8e478109 100644 --- a/DNN Platform/Library/Entities/Host/Host.cs +++ b/DNN Platform/Library/Entities/Host/Host.cs @@ -283,7 +283,7 @@ public static bool DisplayBetaNotice /// /// Defaults to True. /// - [Obsolete("Deprecated in 9.9.2. Scheduled for removal in v11.0.0")] + [Obsolete("Deprecated in DotNetNuke 9.9.2. No replacement. Scheduled removal in v11.0.0.")] public static bool DisplayCopyright { get @@ -335,7 +335,7 @@ public static bool DebugMode } /// Gets a value indicating whether gets whether the installation participates in the improvements program. - [Obsolete("Improvement program functionality removed in 9.7.3. API Scheduled for removal in 10.0.0.")] + [Obsolete("Deprecated in DotNetNuke 9.7.3. No replacement. Scheduled removal in v10.0.0.")] public static bool ParticipateInImprovementProg { get @@ -453,7 +453,7 @@ public static bool EnableUrlLanguage /// /// Defaults to False. /// - [Obsolete("Support for users online was removed in 8.x, other solutions exist outside of the DNN Platform. Scheduled removal in v11.0.0.")] + [Obsolete("Deprecated in DotNetNuke 8.0.0. Other solutions exist outside of the DNN Platform. Scheduled removal in v11.0.0.")] public static bool EnableUsersOnline { get @@ -479,6 +479,27 @@ public static bool EnableSMTPSSL } } + /// ----------------------------------------------------------------------------- + /// + /// Gets the currently configured SMTP OAuth provider if existing, for the current portal if portal SMTP enabled, otherwise for the installation. + /// + /// + /// Defaults to empty string. + /// + /// ----------------------------------------------------------------------------- + public static string SMTPAuthProvider + { + get + { + if (SMTPPortalEnabled) + { + return PortalController.GetPortalSetting("SMTPAuthProvider", PortalSettings.Current.PortalId, string.Empty); + } + + return HostController.Instance.GetString("SMTPAuthProvider", string.Empty); + } + } + /// Gets a value indicating whether gets whether the Event Log Buffer is Enabled. /// /// Defaults to False. @@ -928,7 +949,7 @@ public static bool ShowCriticalErrors /// /// Defaults to 1. /// - [Obsolete("Deprecated in 8.0.0. Scheduled removal in v11.0.0.")] + [Obsolete("Deprecated in DotNetNuke 8.0.0. No replacement. Scheduled removal in v11.0.0.")] public static int SiteLogBuffer { get @@ -941,7 +962,7 @@ public static int SiteLogBuffer /// /// Defaults to -1. /// - [Obsolete("Deprecated in 8.0.0. Scheduled removal in v11.0.0.")] + [Obsolete("Deprecated in DotNetNuke 8.0.0. No replacement. Scheduled removal in vremoval.0.0.")] public static int SiteLogHistory { get @@ -954,7 +975,7 @@ public static int SiteLogHistory /// /// Defaults to "D". /// - [Obsolete("Deprecated in 8.0.0. Scheduled removal in v11.0.0.")] + [Obsolete("Deprecated in DotNetNuke 8.0.0. No replacement. Scheduled removal in v11.0.0.")] public static string SiteLogStorage { get @@ -1104,7 +1125,7 @@ public static int UserQuota /// Gets the window to use in minutes when determining if the user is online. /// Defaults to 15. - [Obsolete("Support for users online was removed in 8.x, other solutions exist outside of the DNN Platform. Scheduled removal in v11.0.0.")] + [Obsolete("Deprecated in DotNetNuke 8.0.0. Other solutions exist outside of the DNN Platform. Scheduled removal in v11.0.0.")] public static int UsersOnlineTimeWindow { get @@ -1129,7 +1150,7 @@ public static int WebRequestTimeout /// /// Defaults to False. /// - [Obsolete("This is managed through the JavaScript Library package. Scheduled removal in v10.0.0.")] + [Obsolete("Deprecated in DotNetNuke 7.3.1. This is managed through the JavaScript Library package. Scheduled removal in v10.0.0.")] [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1300:ElementMustBeginWithUpperCaseLetter", Justification = "Breaking Change")] // ReSharper disable once InconsistentNaming @@ -1145,7 +1166,7 @@ public static bool jQueryDebug /// /// Defaults to False. /// - [Obsolete("This is managed through the JavaScript Library package. Scheduled removal in v10.0.0.")] + [Obsolete("Deprecated in DotNetNuke 7.3.1. This is managed through the JavaScript Library package. Scheduled removal in v10.0.0.")] [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1300:ElementMustBeginWithUpperCaseLetter", Justification = "Breaking Change")] // ReSharper disable once InconsistentNaming @@ -1162,7 +1183,7 @@ public static bool jQueryHosted /// Defaults to the DefaultHostedUrl constant in the jQuery class. /// The framework will default to the latest released 1.x version hosted on Google. /// - [Obsolete("This is managed through the JavaScript Library package. Scheduled removal in v10.0.0.")] + [Obsolete("Deprecated in DotNetNuke 7.3.1. This is managed through the JavaScript Library package. Scheduled removal in v10.0.0.")] [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1300:ElementMustBeginWithUpperCaseLetter", Justification = "Breaking Change")] // ReSharper disable once InconsistentNaming @@ -1186,7 +1207,7 @@ public static string jQueryUrl /// Defaults to the DefaultHostedUrl constant in the jQuery class. /// The framework will default to the latest released 1.x version hosted on Google. /// - [Obsolete("This is managed through the JavaScript Library package. Scheduled removal in v10.0.0.")] + [Obsolete("Deprecated in DotNetNuke 7.3.1. This is managed through the JavaScript Library package. Scheduled removal in v10.0.0.")] [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1300:ElementMustBeginWithUpperCaseLetter", Justification = "Breaking Change")] // ReSharper disable once InconsistentNaming @@ -1210,7 +1231,7 @@ public static string jQueryMigrateUrl /// Defaults to the DefaultUIHostedUrl constant in the jQuery class. /// The framework will default to the latest released 1.x version hosted on Google. /// - [Obsolete("This is managed through the JavaScript Library package. Scheduled removal in v10.0.0.")] + [Obsolete("Deprecated in DotNetNuke 7.3.1. This is managed through the JavaScript Library package. Scheduled removal in v10.0.0.")] [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1300:ElementMustBeginWithUpperCaseLetter", Justification = "Breaking Change")] // ReSharper disable once InconsistentNaming @@ -1245,7 +1266,7 @@ public static bool EnableMsAjaxCdn /// /// Defaults to False. /// - [Obsolete("Not used anymore. Scheduled removal in v10.0.0.")] + [Obsolete("Deprecated in DotNetNuke 9.1.0. No replacement. Scheduled removal in v10.0.0.")] public static bool EnableTelerikCdn { get @@ -1255,7 +1276,7 @@ public static bool EnableTelerikCdn } /// Gets get Telerik CDN Basic Path. - [Obsolete("Not used anymore. Scheduled removal in v10.0.0.")] + [Obsolete("Deprecated in DotNetNuke 9.1.0. No replacement. Scheduled removal in v10.0.0.")] public static string TelerikCdnBasicUrl { get @@ -1265,7 +1286,7 @@ public static string TelerikCdnBasicUrl } /// Gets get Telerik CDN Secure Path. - [Obsolete("Not used anymore. Scheduled removal in v10.0.0.")] + [Obsolete("Deprecated in DotNetNuke 9.1.0. No replacement. Scheduled removal in v10.0.0.")] public static string TelerikCdnSecureUrl { get diff --git a/DNN Platform/Library/Entities/Host/ServerController.cs b/DNN Platform/Library/Entities/Host/ServerController.cs index e17a276c92d..479519642af 100644 --- a/DNN Platform/Library/Entities/Host/ServerController.cs +++ b/DNN Platform/Library/Entities/Host/ServerController.cs @@ -1,69 +1,69 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information -namespace DotNetNuke.Entities.Host -{ - using System; - using System.Collections.Generic; +namespace DotNetNuke.Entities.Host +{ + using System; + using System.Collections.Generic; using System.Linq; using System.Runtime.CompilerServices; - using System.Web.Caching; - - using DotNetNuke.Common; - using DotNetNuke.Common.Utilities; - using DotNetNuke.Data; - using DotNetNuke.Entities.Controllers; - using DotNetNuke.Framework; - using DotNetNuke.Instrumentation; + using System.Web.Caching; + + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Data; + using DotNetNuke.Entities.Controllers; + using DotNetNuke.Framework; + using DotNetNuke.Instrumentation; using DotNetNuke.Services.Log.EventLog; using DotNetNuke.UI.WebControls; - public class ServerController - { - public const string DefaultUrlAdapter = "DotNetNuke.Entities.Host.ServerWebRequestAdapter, DotNetNuke"; - - private const string CacheKey = "WebServers"; - private const int CacheTimeout = 20; - private const CacheItemPriority CachePriority = CacheItemPriority.High; - private static readonly DataProvider DataProvider = DataProvider.Instance(); - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(ServerController)); - - public static bool UseAppName - { - get - { - var uniqueServers = new Dictionary(); - foreach (ServerInfo server in GetEnabledServers()) - { - uniqueServers[server.ServerName] = server.IISAppName; - } - - return uniqueServers.Count < GetEnabledServers().Count; - } - } - - public static void ClearCachedServers() - { - DataCache.RemoveCache(CacheKey); - } - - public static void DeleteServer(int serverID) - { - DataProvider.Instance().DeleteServer(serverID); - ClearCachedServers(); - } - - public static List GetEnabledServers() - { - return GetServers()?.Where(i => i.Enabled).ToList() ?? new List(); + public class ServerController + { + public const string DefaultUrlAdapter = "DotNetNuke.Entities.Host.ServerWebRequestAdapter, DotNetNuke"; + + private const string CacheKey = "WebServers"; + private const int CacheTimeout = 20; + private const CacheItemPriority CachePriority = CacheItemPriority.High; + private static readonly DataProvider DataProvider = DataProvider.Instance(); + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(ServerController)); + + public static bool UseAppName + { + get + { + var uniqueServers = new Dictionary(); + foreach (ServerInfo server in GetEnabledServers()) + { + uniqueServers[server.ServerName] = server.IISAppName; + } + + return uniqueServers.Count < GetEnabledServers().Count; + } + } + + public static void ClearCachedServers() + { + DataCache.RemoveCache(CacheKey); + } + + public static void DeleteServer(int serverID) + { + DataProvider.Instance().DeleteServer(serverID); + ClearCachedServers(); + } + + public static List GetEnabledServers() + { + return GetServers()?.Where(i => i.Enabled).ToList() ?? new List(); } /// /// Gets the servers, order by last activity date in descending order. /// - /// The number of recent minutes activity had to occur - /// A list of servers with activity within the specified minutes - public static List GetEnabledServersWithActivity(int lastMinutes = 10) + /// The number of recent minutes activity had to occur. + /// A list of servers with activity within the specified minutes. + public static List GetEnabledServersWithActivity(int lastMinutes = 10) { return GetServersNoCache() .Where(i => i.Enabled == true && DateTime.Now.Subtract(i.LastActivityDate).TotalMinutes <= lastMinutes) @@ -74,71 +74,71 @@ public static List GetEnabledServersWithActivity(int lastMinutes = 1 /// /// Gets the servers, that have no activtiy in the specified time frame. /// - /// The number of recent minutes activity had to occur - /// A list of servers with no activity for the specified minutes. Defaults to 24 hours - public static List GetInActiveServers(int lastMinutes = 1440) + /// The number of recent minutes activity had to occur. + /// A list of servers with no activity for the specified minutes. Defaults to 24 hours. + public static List GetInActiveServers(int lastMinutes = 1440) { return GetServersNoCache() .Where(i => DateTime.Now.Subtract(i.LastActivityDate).TotalMinutes > lastMinutes && i.ServerName != Environment.MachineName) .OrderByDescending(i => i.LastActivityDate) .ToList(); - } - - public static string GetExecutingServerName() - { - string executingServerName = Globals.ServerName; - if (UseAppName) - { - executingServerName += "-" + Globals.IISAppName; - } - - Logger.Debug("GetExecutingServerName:" + executingServerName); - return executingServerName; - } - - public static string GetServerName(ServerInfo webServer) - { - string serverName = webServer.ServerName; - if (UseAppName) - { - serverName += "-" + webServer.IISAppName; - } - - Logger.Debug("GetServerName:" + serverName); - return serverName; - } - - public static List GetServers() - { - var servers = CBO.GetCachedObject>(new CacheItemArgs(CacheKey, CacheTimeout, CachePriority), GetServersCallBack); - return servers; - } - - public static void UpdateServer(ServerInfo server) - { - DataProvider.Instance().UpdateServer(server.ServerID, server.Url, server.UniqueId, server.Enabled, server.ServerGroup); - ClearCachedServers(); - } - - public static void UpdateServerActivity(ServerInfo server) - { - var allServers = GetServers(); - var existServer = allServers.FirstOrDefault(s => s.ServerName == server.ServerName && s.IISAppName == server.IISAppName); - var serverId = DataProvider.Instance().UpdateServerActivity(server.ServerName, server.IISAppName, server.CreatedDate, server.LastActivityDate, server.PingFailureCount, server.Enabled); - - server.ServerID = serverId; - if (existServer == null - || string.IsNullOrEmpty(existServer.Url) - || (string.IsNullOrEmpty(existServer.UniqueId) && !string.IsNullOrEmpty(GetServerUniqueId()))) - { - // try to detect the server url from url adapter. - server.Url = existServer == null || string.IsNullOrEmpty(existServer.Url) ? GetServerUrl() : existServer.Url; - - // try to detect the server unique id from url adapter. - server.UniqueId = existServer == null || string.IsNullOrEmpty(existServer.UniqueId) ? GetServerUniqueId() : existServer.UniqueId; - + } + + public static string GetExecutingServerName() + { + string executingServerName = Globals.ServerName; + if (UseAppName) + { + executingServerName += "-" + Globals.IISAppName; + } + + Logger.Debug("GetExecutingServerName:" + executingServerName); + return executingServerName; + } + + public static string GetServerName(ServerInfo webServer) + { + string serverName = webServer.ServerName; + if (UseAppName) + { + serverName += "-" + webServer.IISAppName; + } + + Logger.Debug("GetServerName:" + serverName); + return serverName; + } + + public static List GetServers() + { + var servers = CBO.GetCachedObject>(new CacheItemArgs(CacheKey, CacheTimeout, CachePriority), GetServersCallBack); + return servers; + } + + public static void UpdateServer(ServerInfo server) + { + DataProvider.Instance().UpdateServer(server.ServerID, server.Url, server.UniqueId, server.Enabled, server.ServerGroup); + ClearCachedServers(); + } + + public static void UpdateServerActivity(ServerInfo server) + { + var allServers = GetServers(); + var existServer = allServers.FirstOrDefault(s => s.ServerName == server.ServerName && s.IISAppName == server.IISAppName); + var serverId = DataProvider.Instance().UpdateServerActivity(server.ServerName, server.IISAppName, server.CreatedDate, server.LastActivityDate, server.PingFailureCount, server.Enabled); + + server.ServerID = serverId; + if (existServer == null + || string.IsNullOrEmpty(existServer.Url) + || (string.IsNullOrEmpty(existServer.UniqueId) && !string.IsNullOrEmpty(GetServerUniqueId()))) + { + // try to detect the server url from url adapter. + server.Url = existServer == null || string.IsNullOrEmpty(existServer.Url) ? GetServerUrl() : existServer.Url; + + // try to detect the server unique id from url adapter. + server.UniqueId = existServer == null || string.IsNullOrEmpty(existServer.UniqueId) ? GetServerUniqueId() : existServer.UniqueId; + UpdateServer(server); - ClearCachedServers(); // Only clear the cache if we added a server + ClearCachedServers(); // Only clear the cache if we added a server } else { @@ -146,71 +146,71 @@ public static void UpdateServerActivity(ServerInfo server) existServer.LastActivityDate = server.LastActivityDate; existServer.Enabled = server.Enabled; DataCache.SetCache(ServerController.CacheKey, allServers); - } - - // log the server info + } + + // log the server info var log = new LogInfo(); - log.AddProperty(existServer != null ? "Server Updated" : "Add New Server", server.ServerName); - log.AddProperty("IISAppName", server.IISAppName); - log.AddProperty("Last Activity Date", server.LastActivityDate.ToString()); - log.LogTypeKey = existServer != null ? EventLogController.EventLogType.WEBSERVER_UPDATED.ToString() - : EventLogController.EventLogType.WEBSERVER_CREATED.ToString(); - LogController.Instance.AddLog(log); - } - - public static IServerWebRequestAdapter GetServerWebRequestAdapter() - { - var adapterConfig = HostController.Instance.GetString("WebServer_ServerRequestAdapter", DefaultUrlAdapter); - var adapterType = Reflection.CreateType(adapterConfig); - return Reflection.CreateInstance(adapterType) as IServerWebRequestAdapter; - } - - private static List GetServersNoCache() - { - return CBO.FillCollection(DataProvider.GetServers()); - } - - private static object GetServersCallBack(CacheItemArgs cacheItemArgs) - { - return CBO.FillCollection(DataProvider.GetServers()); - } - - private static string GetServerUrl() - { - try - { - var adpapter = GetServerWebRequestAdapter(); - if (adpapter == null) - { - return string.Empty; - } - - return adpapter.GetServerUrl(); - } - catch (Exception ex) - { - Logger.Error(ex); - return string.Empty; - } - } - - private static string GetServerUniqueId() - { - try - { - var adpapter = GetServerWebRequestAdapter(); - if (adpapter == null) - { - return string.Empty; - } - - return adpapter.GetServerUniqueId(); - } - catch (Exception ex) - { - Logger.Error(ex); - return string.Empty; - } - } - } -} + log.AddProperty(existServer != null ? "Server Updated" : "Add New Server", server.ServerName); + log.AddProperty("IISAppName", server.IISAppName); + log.AddProperty("Last Activity Date", server.LastActivityDate.ToString()); + log.LogTypeKey = existServer != null ? EventLogController.EventLogType.WEBSERVER_UPDATED.ToString() + : EventLogController.EventLogType.WEBSERVER_CREATED.ToString(); + LogController.Instance.AddLog(log); + } + + public static IServerWebRequestAdapter GetServerWebRequestAdapter() + { + var adapterConfig = HostController.Instance.GetString("WebServer_ServerRequestAdapter", DefaultUrlAdapter); + var adapterType = Reflection.CreateType(adapterConfig); + return Reflection.CreateInstance(adapterType) as IServerWebRequestAdapter; + } + + private static List GetServersNoCache() + { + return CBO.FillCollection(DataProvider.GetServers()); + } + + private static object GetServersCallBack(CacheItemArgs cacheItemArgs) + { + return CBO.FillCollection(DataProvider.GetServers()); + } + + private static string GetServerUrl() + { + try + { + var adpapter = GetServerWebRequestAdapter(); + if (adpapter == null) + { + return string.Empty; + } + + return adpapter.GetServerUrl(); + } + catch (Exception ex) + { + Logger.Error(ex); + return string.Empty; + } + } + + private static string GetServerUniqueId() + { + try + { + var adpapter = GetServerWebRequestAdapter(); + if (adpapter == null) + { + return string.Empty; + } + + return adpapter.GetServerUniqueId(); + } + catch (Exception ex) + { + Logger.Error(ex); + return string.Empty; + } + } + } +} diff --git a/DNN Platform/Library/Entities/IPFilter/IIPFilterController.cs b/DNN Platform/Library/Entities/IPFilter/IIPFilterController.cs index d8f37b3841d..37b3d40e25a 100644 --- a/DNN Platform/Library/Entities/IPFilter/IIPFilterController.cs +++ b/DNN Platform/Library/Entities/IPFilter/IIPFilterController.cs @@ -37,7 +37,7 @@ public interface IIPFilterController /// Gets a value indicating whether a given IP address is banned. /// A string representation of an IP address. - [Obsolete("deprecated with 7.1.0 - please use IsIPBanned instead. Scheduled removal in v10.0.0.")] + [Obsolete("Deprecated in DotNetNuke 7.1.0. Please use IsIPBanned instead. Scheduled removal in v10.0.0.")] void IsIPAddressBanned(string ipAddress); /// Gets a value indicating whether a given IP address is banned. diff --git a/DNN Platform/Library/Entities/IPFilter/IPFilterController.cs b/DNN Platform/Library/Entities/IPFilter/IPFilterController.cs index 65da7cc94c7..845503cbd4b 100644 --- a/DNN Platform/Library/Entities/IPFilter/IPFilterController.cs +++ b/DNN Platform/Library/Entities/IPFilter/IPFilterController.cs @@ -8,18 +8,19 @@ namespace DotNetNuke.Entities.Host using System.Linq; using System.Net; using System.Web; - + using DotNetNuke.Common; using DotNetNuke.Common.Utilities; using DotNetNuke.Common.Utils; using DotNetNuke.ComponentModel; using DotNetNuke.Data; using DotNetNuke.Entities.Users; + using DotNetNuke.Internal.SourceGenerators; using DotNetNuke.Services.Localization; using DotNetNuke.Services.Log.EventLog; - /// Controller to manage IP Filters. - public class IPFilterController : ComponentBase, IIPFilterController + /// Controller to manage IP Filters. + public partial class IPFilterController : ComponentBase, IIPFilterController { /// Initializes a new instance of the class. internal IPFilterController() @@ -69,22 +70,22 @@ public void DeleteIPFilter(IPFilterInfo ipFilter) DataProvider.Instance().DeleteIPFilter(ipFilter.IPFilterID); } - /// + /// public IPFilterInfo GetIPFilter(int ipFilter) { return CBO.FillObject(DataProvider.Instance().GetIPFilter(ipFilter)); - } - - /// - [Obsolete("deprecated with 7.1.0 - please use IsIPBanned instead to return the value and apply your own logic. Scheduled removal in v10.0.0.")] - public void IsIPAddressBanned(string ipAddress) + } + + /// + [DnnDeprecated(7, 1, 0, "Please use IsIPBanned instead to return the value and apply your own logic", RemovalVersion = 10)] + public partial void IsIPAddressBanned(string ipAddress) { if (this.CheckIfBannedIPAddress(ipAddress)) {// should throw 403.6 throw new HttpException(403, string.Empty); } - } - + } + /// public bool IsIPBanned(string ipAddress) { diff --git a/DNN Platform/Library/Entities/Icons/IconController.cs b/DNN Platform/Library/Entities/Icons/IconController.cs index 597c2307476..0f90dc719da 100644 --- a/DNN Platform/Library/Entities/Icons/IconController.cs +++ b/DNN Platform/Library/Entities/Icons/IconController.cs @@ -6,12 +6,14 @@ namespace DotNetNuke.Entities.Icons using System; using System.IO; using System.Web.Hosting; + using DotNetNuke.Abstractions.Application; using DotNetNuke.Application; using DotNetNuke.Collections.Internal; using DotNetNuke.Common; using DotNetNuke.Entities.Portals; using DotNetNuke.Instrumentation; + using DotNetNuke.Internal.SourceGenerators; using Microsoft.Extensions.DependencyInjection; /// IconController provides all operation to icons. @@ -20,7 +22,7 @@ namespace DotNetNuke.Entities.Icons /// Tabs will be a sitemap for a poatal, and every request at first need to check whether there is valid tab information /// include in the url, if not it will use default tab to display information. /// - public class IconController + public partial class IconController { public const string DefaultIconSize = "16X16"; public const string DefaultLargeIconSize = "32X32"; @@ -90,8 +92,8 @@ public static string GetFileIconUrl(string extension) return IconURL("ExtFile", "32x32", "Standard"); } - [Obsolete("Deprecated in DNN 9.11.1, use overload taking an IApplicationStatusInfo. Scheduled for removal in v11.")] - public static string[] GetIconSets() + [DnnDeprecated(9, 11, 1, "Use overload taking an IApplicationStatusInfo")] + public static partial string[] GetIconSets() { return GetIconSets( Globals.DependencyProvider.GetService() ?? new ApplicationStatusInfo(new Application())); diff --git a/DNN Platform/Library/Entities/Modules/ISearchable.cs b/DNN Platform/Library/Entities/Modules/ISearchable.cs index 9b7f27f7347..a3f1aa484b8 100644 --- a/DNN Platform/Library/Entities/Modules/ISearchable.cs +++ b/DNN Platform/Library/Entities/Modules/ISearchable.cs @@ -1,16 +1,17 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information -namespace DotNetNuke.Entities.Modules -{ - using System; +namespace DotNetNuke.Entities.Modules +{ + using System; + using DotNetNuke.Internal.SourceGenerators; using DotNetNuke.Services.Search; - [Obsolete("Deprecated in DNN 7.1. Replaced by ModuleSearchBase. Scheduled removal in v10.0.0.")] - public interface ISearchable - { - [Obsolete("Deprecated in DNN 7.1. Replaced by ModuleSearchBase.GetModifiedSearchDocuments. Scheduled removal in v10.0.0.")] - SearchItemInfoCollection GetSearchItems(ModuleInfo modInfo); - } -} + [DnnDeprecated(7, 1, 0, "Replaced by ModuleSearchBase", RemovalVersion = 10)] + public partial interface ISearchable + { + [Obsolete("Deprecated in DotNetNuke 7.1.0. Replaced by ModuleSearchBase.GetModifiedSearchDocuments. Scheduled for removal in v10.0.0.")] + SearchItemInfoCollection GetSearchItems(ModuleInfo modInfo); + } +} diff --git a/DNN Platform/Library/Entities/Modules/ModuleInfo.cs b/DNN Platform/Library/Entities/Modules/ModuleInfo.cs index ce557ed99d0..4ad147b08ef 100644 --- a/DNN Platform/Library/Entities/Modules/ModuleInfo.cs +++ b/DNN Platform/Library/Entities/Modules/ModuleInfo.cs @@ -390,7 +390,7 @@ public CacheLevel Cacheability [JsonIgnore] public bool IsShareableViewOnly { get; set; } - [Obsolete("WebSlice functionality is no longer used. Will be removed in v10.0.0")] + [Obsolete("Deprecated in DotNetNuke 9.8.0. WebSlice functionality is no longer used. Scheduled removal in v10.0.0.")] [XmlElement("iswebslice")] public bool IsWebSlice { get; set; } @@ -476,15 +476,15 @@ public ModulePermissionCollection ModulePermissions [XmlElement("visibility")] public VisibilityState Visibility { get; set; } - [Obsolete("WebSlice functionality is no longer used. Will be removed in v10.0.0")] + [Obsolete("Deprecated in DotNetNuke 9.8.0. WebSlice functionality is no longer used. Scheduled removal in v10.0.0.")] [XmlElement("websliceexpirydate")] public DateTime WebSliceExpiryDate { get; set; } - [Obsolete("WebSlice functionality is no longer used. Will be removed in v10.0.0")] + [Obsolete("Deprecated in DotNetNuke 9.8.0. WebSlice functionality is no longer used. Scheduled removal in v10.0.0.")] [XmlElement("webslicetitle")] public string WebSliceTitle { get; set; } - [Obsolete("WebSlice functionality is no longer used. Will be removed in v10.0.0")] + [Obsolete("Deprecated in DotNetNuke 9.8.0. WebSlice functionality is no longer used. Scheduled removal in v10.0.0.")] [XmlElement("webslicettl")] public int WebSliceTTL { get; set; } diff --git a/DNN Platform/Library/Entities/Modules/PortalModuleBase.cs b/DNN Platform/Library/Entities/Modules/PortalModuleBase.cs index 60e6ddacaa3..41df6b3dc07 100644 --- a/DNN Platform/Library/Entities/Modules/PortalModuleBase.cs +++ b/DNN Platform/Library/Entities/Modules/PortalModuleBase.cs @@ -17,6 +17,7 @@ namespace DotNetNuke.Entities.Modules using DotNetNuke.Entities.Users; using DotNetNuke.Framework; using DotNetNuke.Instrumentation; + using DotNetNuke.Internal.SourceGenerators; using DotNetNuke.Services.Localization; using DotNetNuke.UI.Modules; @@ -30,7 +31,7 @@ namespace DotNetNuke.Entities.Modules /// The PortalModuleBase class defines portal specific properties /// that are used by the portal framework to correctly display portal modules. /// - public class PortalModuleBase : UserControlBase, IModuleControl + public partial class PortalModuleBase : UserControlBase, IModuleControl { protected static readonly Regex FileInfoRegex = new Regex( @"\.([a-z]{2,3}\-[0-9A-Z]{2,4}(-[A-Z]{2})?)(\.(Host|Portal-\d+))?\.resx$", @@ -186,7 +187,7 @@ public ModuleInstanceContext ModuleContext /// Gets the CacheDirectory property is used to return the location of the "Cache" /// Directory for the Module. /// - [Obsolete("This property is deprecated. Plaese use ModuleController.CacheDirectory(). Scheduled removal in v11.0.0.")] + [Obsolete("Deprecated in DotNetNuke 7.0.0. Please use ModuleController.CacheDirectory(). Scheduled removal in v11.0.0.")] public string CacheDirectory { get @@ -199,7 +200,7 @@ public string CacheDirectory /// Gets the CacheFileName property is used to store the FileName for this Module's /// Cache. /// - [Obsolete("This property is deprecated. Please use ModuleController.CacheFileName(TabModuleID). Scheduled removal in v11.0.0.")] + [Obsolete("Deprecated in DotNetNuke 7.0.0. Please use ModuleController.CacheFileName(TabModuleID). Scheduled removal in v11.0.0.")] public string CacheFileName { get @@ -211,7 +212,7 @@ public string CacheFileName } } - [Obsolete("This property is deprecated. Please use ModuleController.CacheKey(TabModuleID). Scheduled removal in v11.0.0.")] + [Obsolete("Deprecated in DotNetNuke 7.0.0. Please use ModuleController.CacheKey(TabModuleID). Scheduled removal in v11.0.0.")] public string CacheKey { get @@ -387,8 +388,8 @@ public override void Dispose() } } - [Obsolete("This property is deprecated. Please use ModuleController.CacheFileName(TabModuleID). Scheduled removal in v11.0.0.")] - public string GetCacheFileName(int tabModuleId) + [DnnDeprecated(7, 0, 0, "Please use ModuleController.CacheFileName(TabModuleID)", RemovalVersion = 11)] + public partial string GetCacheFileName(int tabModuleId) { string strCacheKey = "TabModule:"; strCacheKey += tabModuleId + ":"; @@ -396,8 +397,8 @@ public string GetCacheFileName(int tabModuleId) return PortalController.Instance.GetCurrentPortalSettings().HomeDirectoryMapPath + "Cache" + "\\" + Globals.CleanFileName(strCacheKey) + ".resources"; } - [Obsolete("This property is deprecated. Please use ModuleController.CacheKey(TabModuleID). Scheduled removal in v11.0.0.")] - public string GetCacheKey(int tabModuleId) + [DnnDeprecated(7, 0, 0, "Please use ModuleController.CacheKey(TabModuleID)", RemovalVersion = 11)] + public partial string GetCacheKey(int tabModuleId) { string strCacheKey = "TabModule:"; strCacheKey += tabModuleId + ":"; @@ -405,8 +406,8 @@ public string GetCacheKey(int tabModuleId) return strCacheKey; } - [Obsolete("This method is deprecated. Plaese use ModuleController.SynchronizeModule(ModuleId). Scheduled removal in v11.0.0.")] - public void SynchronizeModule() + [DnnDeprecated(7, 0, 0, "Please use ModuleController.SynchronizeModule(ModuleId)", RemovalVersion = 11)] + public partial void SynchronizeModule() { ModuleController.SynchronizeModule(this.ModuleId); } diff --git a/DNN Platform/Library/Entities/Modules/Settings/SettingsRepository.cs b/DNN Platform/Library/Entities/Modules/Settings/SettingsRepository.cs index 48a8d0daae9..28ace91909c 100644 --- a/DNN Platform/Library/Entities/Modules/Settings/SettingsRepository.cs +++ b/DNN Platform/Library/Entities/Modules/Settings/SettingsRepository.cs @@ -50,7 +50,7 @@ protected virtual string MappingCacheKey /// public T GetSettings(ModuleInfo moduleContext) { - return CBO.GetCachedObject(new CacheItemArgs(this.CacheKey(moduleContext.TabModuleID), 20, CacheItemPriority.AboveNormal, moduleContext), this.Load, false); + return CBO.GetCachedObject(new CacheItemArgs(this.CacheKey(moduleContext.PortalID), 20, CacheItemPriority.AboveNormal, moduleContext), this.Load, false); } /// @@ -164,7 +164,7 @@ private void SaveSettings(int portalId, ModuleInfo moduleContext, T settings) } } }); - DataCache.SetCache(this.CacheKey(moduleContext == null ? portalId : moduleContext.TabModuleID), settings); + DataCache.SetCache(this.CacheKey(portalId), settings); } private T Load(CacheItemArgs args) diff --git a/DNN Platform/Library/Entities/Portals/IPortalController.cs b/DNN Platform/Library/Entities/Portals/IPortalController.cs index f6cd5322712..c4b324b4047 100644 --- a/DNN Platform/Library/Entities/Portals/IPortalController.cs +++ b/DNN Platform/Library/Entities/Portals/IPortalController.cs @@ -39,7 +39,7 @@ public interface IPortalController /// The child path. /// if set to true means the portal is child portal. /// Portal id. - [Obsolete("Deprecated in DNN 9.11.1. Use DotNetNuke.Entities.Portals.Templates.PortalTemplateInfo template argument instead. Scheduled removal in v11.0.0.")] + [Obsolete("Deprecated in DotNetNuke 9.11.1. Use DotNetNuke.Entities.Portals.Templates.PortalTemplateInfo template argument instead. Scheduled removal in v11.0.0.")] int CreatePortal(string portalName, int adminUserId, string description, string keyWords, PortalController.PortalTemplateInfo template, string homeDirectory, string portalAlias, string serverPath, string childPath, bool isChildPortal); /// Creates the portal. @@ -68,7 +68,7 @@ public interface IPortalController /// The child path. /// if set to true means the portal is child portal. /// Portal id. - [Obsolete("Deprecated in DNN 9.11.1. Use IPortalTemplateInfo template argument instead. Scheduled removal in v11.0.0.")] + [Obsolete("Deprecated in DotNetNuke 9.11.1. Use IPortalTemplateInfo template argument instead. Scheduled removal in v11.0.0.")] int CreatePortal(string portalName, UserInfo adminUser, string description, string keyWords, PortalController.PortalTemplateInfo template, string homeDirectory, string portalAlias, string serverPath, string childPath, bool isChildPortal); /// Creates the portal. @@ -87,12 +87,12 @@ public interface IPortalController /// Get all the available portal templates grouped by culture. /// List of PortalTemplateInfo objects. - [Obsolete("Deprecated in DNN 9.11.1. Use DotNetNuke.Entities.Portals.Templates.PortalTemplateController.Instance.GetPortalTemplates instead. Scheduled removal in v11.0.0.")] + [Obsolete("Deprecated in DotNetNuke 9.11.1. Use DotNetNuke.Entities.Portals.Templates.PortalTemplateController.Instance.GetPortalTemplates instead. Scheduled removal in v11.0.0.")] IList GetAvailablePortalTemplates(); /// Gets the current portal settings. /// portal settings. - [Obsolete("Deprecated in Platform 9.4.2. Scheduled removal in v11.0.0. Use GetCurrentSettings instead.")] + [Obsolete("Deprecated in DotNetNuke 9.4.2. Use GetCurrentSettings instead. Scheduled removal in v11.0.0.")] PortalSettings GetCurrentPortalSettings(); /// Gets the current portal settings. @@ -144,7 +144,7 @@ public interface IPortalController /// The file name of the portal template. /// the culture code if any for the localization of the portal template. /// A portal template. - [Obsolete("Deprecated in DNN 9.11.1. Use DotNetNuke.Entities.Portals.Templates.PortalTemplateController.Instance.GetPortalTemplate instead. Scheduled removal in v11.0.0.")] + [Obsolete("Deprecated in DotNetNuke 9.11.1. Use DotNetNuke.Entities.Portals.Templates.PortalTemplateController.Instance.GetPortalTemplate instead. Scheduled removal in v11.0.0.")] PortalController.PortalTemplateInfo GetPortalTemplate(string templateFileName, string cultureCode); /// Verifies if there's enough space to upload a new file on the given portal. @@ -174,7 +174,7 @@ public interface IPortalController /// /// The roles and settings nodes will only be processed on the portal template file. /// - [Obsolete("Deprecated in DNN 9.11.1. Use DotNetNuke.Entities.Portals.Templates.PortalTemplateController.Instance.ApplyPortalTemplate instead. Scheduled removal in v11.0.0.")] + [Obsolete("Deprecated in DotNetNuke 9.11.1. Use DotNetNuke.Entities.Portals.Templates.PortalTemplateController.Instance.ApplyPortalTemplate instead. Scheduled removal in v11.0.0.")] void ParseTemplate(int portalId, PortalController.PortalTemplateInfo template, int administratorId, PortalTemplateModuleAction mergeTabs, bool isNewPortal); /// Processes the resource file for the template file selected. @@ -196,7 +196,7 @@ public interface IPortalController /// void UpdatePortalInfo(PortalInfo portal); - [Obsolete("Deprecated in DNN 9.2.0. Use the overloaded one with the 'isSecure' parameter instead. Scheduled removal in v11.0.0.")] + [Obsolete("Deprecated in DotNetNuke 9.2.0. Use the overloaded one with the 'isSecure' parameter instead. Scheduled removal in v11.0.0.")] void UpdatePortalSetting(int portalID, string settingName, string settingValue, bool clearCache, string cultureCode); /// Adds or Updates or Deletes a portal setting value. diff --git a/DNN Platform/Library/Entities/Portals/PortalAliasCollection.cs b/DNN Platform/Library/Entities/Portals/PortalAliasCollection.cs index bb91e4745ef..ff68118f3f6 100644 --- a/DNN Platform/Library/Entities/Portals/PortalAliasCollection.cs +++ b/DNN Platform/Library/Entities/Portals/PortalAliasCollection.cs @@ -7,12 +7,13 @@ namespace DotNetNuke.Entities.Portals using System; using System.Collections; + using DotNetNuke.Internal.SourceGenerators; + [Serializable] - [Obsolete("Deprecated in 9.7.2. Scheduled for removal in v11.0.0, use IDictionary instead.")] - public class PortalAliasCollection : DictionaryBase + [DnnDeprecated(9, 7, 2, "use IDictionary instead")] + public partial class PortalAliasCollection : DictionaryBase { /// Gets a value indicating whether gets a value indicating if the collection contains keys that are not null. - [Obsolete("Deprecated in 9.7.2. Scheduled for removal in v11.0.0, use IDictionary instead.")] public bool HasKeys { get @@ -21,7 +22,6 @@ public bool HasKeys } } - [Obsolete("Deprecated in 9.7.2. Scheduled for removal in v11.0.0, use IDictionary instead.")] public ICollection Keys { get @@ -30,7 +30,6 @@ public ICollection Keys } } - [Obsolete("Deprecated in 9.7.2. Scheduled for removal in v11.0.0, use IDictionary instead.")] public ICollection Values { get @@ -40,7 +39,6 @@ public ICollection Values } /// Gets or sets the value associated with the specified key. - [Obsolete("Deprecated in 9.7.2. Scheduled for removal in v11.0.0, use IDictionary instead.")] public PortalAliasInfo this[string key] { get @@ -54,15 +52,15 @@ public PortalAliasInfo this[string key] } } - [Obsolete("Deprecated in 9.7.2. Scheduled for removal in v11.0.0, use IDictionary instead.")] - public bool Contains(string key) + [DnnDeprecated(9, 7, 2, "use IDictionary instead")] + public partial bool Contains(string key) { return this.Dictionary.Contains(key); } /// Adds an entry to the collection. - [Obsolete("Deprecated in 9.7.2. Scheduled for removal in v11.0.0, use IDictionary instead.")] - public void Add(string key, PortalAliasInfo value) + [DnnDeprecated(9, 7, 2, "use IDictionary instead")] + public partial void Add(string key, PortalAliasInfo value) { this.Dictionary.Add(key, value); } diff --git a/DNN Platform/Library/Entities/Portals/PortalAliasInfo.cs b/DNN Platform/Library/Entities/Portals/PortalAliasInfo.cs index 19a463e202f..fc249fbd924 100644 --- a/DNN Platform/Library/Entities/Portals/PortalAliasInfo.cs +++ b/DNN Platform/Library/Entities/Portals/PortalAliasInfo.cs @@ -50,7 +50,7 @@ public PortalAliasInfo(IPortalAliasInfo alias) /// string IPortalAliasInfo.HttpAlias { get; set; } - [Obsolete("Deprecated in 9.7.2. Scheduled for removal in v11.0.0, use DotNetNuke.Abstractions.Portals.IPortalAliasInfo.HttpAlias instead.")] + [Obsolete("Deprecated in DotNetNuke 9.7.2. Use DotNetNuke.Abstractions.Portals.IPortalAliasInfo.HttpAlias instead. Scheduled removal in v11.0.0.")] public string HTTPAlias { get => this.ThisAsInterface.HttpAlias; @@ -60,7 +60,7 @@ public string HTTPAlias /// int IPortalAliasInfo.PortalAliasId { get; set; } - [Obsolete("Deprecated in 9.7.2. Scheduled for removal in v11.0.0, use DotNetNuke.Abstractions.Portals.IPortalAliasInfo.PortalAliasId instead.")] + [Obsolete("Deprecated in DotNetNuke 9.7.2. Use DotNetNuke.Abstractions.Portals.IPortalAliasInfo.PortalAliasId instead. Scheduled removal in v11.0.0.")] public int PortalAliasID { get => this.ThisAsInterface.PortalAliasId; @@ -70,7 +70,7 @@ public int PortalAliasID /// int IPortalAliasInfo.PortalId { get; set; } - [Obsolete("Deprecated in 9.7.2. Scheduled for removal in v11.0.0, use DotNetNuke.Abstractions.Portals.IPortalAliasInfo.PortalId instead.")] + [Obsolete("Deprecated in DotNetNuke 9.7.2. Use DotNetNuke.Abstractions.Portals.IPortalAliasInfo.PortalId instead. Scheduled removal in v11.0.0.")] public int PortalID { get => this.ThisAsInterface.PortalId; @@ -84,7 +84,7 @@ public int PortalID public bool Redirect { get; set; } /// Gets or sets the Browser Type. - [Obsolete("Deprecated in 9.7.2. Scheduled for removal in v11.0.0, use DotNetNuke.Abstractions.Portals.IPortalAliasInfo.BrowserType instead.")] + [Obsolete("Deprecated in DotNetNuke 9.7.2. Use DotNetNuke.Abstractions.Portals.IPortalAliasInfo.BrowserType instead. Scheduled removal in v11.0.0.")] public BrowserTypes BrowserType { get => (BrowserTypes)this.ThisAsInterface.BrowserType; diff --git a/DNN Platform/Library/Entities/Portals/PortalController.cs b/DNN Platform/Library/Entities/Portals/PortalController.cs index 6f0f46d4ec2..6a63dc94bdf 100644 --- a/DNN Platform/Library/Entities/Portals/PortalController.cs +++ b/DNN Platform/Library/Entities/Portals/PortalController.cs @@ -35,6 +35,7 @@ namespace DotNetNuke.Entities.Portals using DotNetNuke.Entities.Users.Social; using DotNetNuke.Framework; using DotNetNuke.Instrumentation; + using DotNetNuke.Internal.SourceGenerators; using DotNetNuke.Security.Membership; using DotNetNuke.Security.Permissions; using DotNetNuke.Security.Roles; @@ -605,8 +606,8 @@ public static void UpdatePortalSetting(int portalID, string settingName, string /// Name of the setting. /// The setting value. /// culture code for language specific settings, null string ontherwise. - [Obsolete("Deprecated in DNN 9.2.0. Use the overloaded one with the 'isSecure' parameter instead. Scheduled removal in v11.0.0.")] - public static void UpdatePortalSetting(int portalID, string settingName, string settingValue, string cultureCode) + [DnnDeprecated(9, 2, 0, "Use the overload with the 'isSecure' parameter instead")] + public static partial void UpdatePortalSetting(int portalID, string settingName, string settingValue, string cultureCode) { UpdatePortalSetting(portalID, settingName, settingValue, true, cultureCode, false); } @@ -989,8 +990,8 @@ public int CreatePortal(string portalName, UserInfo adminUser, string descriptio /// Get all the available portal templates grouped by culture. /// List of PortalTemplateInfo objects. - [Obsolete("Deprecated in DNN 9.11.1. Use DotNetNuke.Entities.Portals.Templates.PortalTemplateController.Instance.GetPortalTemplates instead. Scheduled removal in v11.0.0.")] - public IList GetAvailablePortalTemplates() + [DnnDeprecated(9, 11, 1, "Use DotNetNuke.Entities.Portals.Templates.PortalTemplateController.Instance.GetPortalTemplates instead")] + public partial IList GetAvailablePortalTemplates() { var list = new List(); @@ -1139,8 +1140,8 @@ public Dictionary GetPortalSettings(int portalId, string culture /// Full path to the portal template. /// the culture code if any for the localization of the portal template. /// A portal template. - [Obsolete("Deprecated in DNN 9.11.1. Use DotNetNuke.Entities.Portals.Templates.PortalTemplateController.Instance.GetPortalTemplate instead. Scheduled removal in v11.0.0.")] - public PortalTemplateInfo GetPortalTemplate(string templatePath, string cultureCode) + [DnnDeprecated(9, 11, 1, "Use DotNetNuke.Entities.Portals.Templates.PortalTemplateController.Instance.GetPortalTemplate instead")] + public partial PortalTemplateInfo GetPortalTemplate(string templatePath, string cultureCode) { var template = new PortalTemplateInfo(templatePath, cultureCode); @@ -1338,8 +1339,8 @@ public void RemovePortalLocalization(int portalId, string cultureCode, bool clea /// /// The roles and settings nodes will only be processed on the portal template file. /// - [Obsolete("Deprecated in DNN 9.11.1. Use DotNetNuke.Entities.Portals.Templates.PortalTemplateController.Instance.ApplyPortalTemplate instead. Scheduled removal in v11.0.0.")] - public void ParseTemplate(int portalId, PortalTemplateInfo template, int administratorId, PortalTemplateModuleAction mergeTabs, bool isNewPortal) + [DnnDeprecated(9, 11, 1, "Use DotNetNuke.Entities.Portals.Templates.PortalTemplateController.Instance.ApplyPortalTemplate instead")] + public partial void ParseTemplate(int portalId, PortalTemplateInfo template, int administratorId, PortalTemplateModuleAction mergeTabs, bool isNewPortal) { var t = new Templates.PortalTemplateInfo(template.TemplateFilePath, template.CultureCode); var portalTemplateImporter = new PortalTemplateImporter(t); @@ -1404,7 +1405,7 @@ IAbPortalSettings IPortalController.GetCurrentSettings() } /// - [Obsolete("Deprecated in DNN 9.2.0. Use the overloaded one with the 'isSecure' parameter instead. Scheduled removal in v11.0.0.")] + [Obsolete("Deprecated in DotNetNuke 9.2.0. Use the overloaded one with the 'isSecure' parameter instead. Scheduled removal in v11.0.0.")] void IPortalController.UpdatePortalSetting(int portalID, string settingName, string settingValue, bool clearCache, string cultureCode) { UpdatePortalSettingInternal(portalID, settingName, settingValue, clearCache, cultureCode, false); @@ -1416,14 +1417,14 @@ void IPortalController.UpdatePortalSetting(int portalID, string settingName, str UpdatePortalSettingInternal(portalID, settingName, settingValue, clearCache, cultureCode, isSecure); } - [Obsolete("Deprecated in DNN 9.11.1. Use DotNetNuke.Entities.Portals.Templates.PortalTemplateInfo instead. Scheduled removal in v11.0.0.")] - public int CreatePortal(string portalName, UserInfo adminUser, string description, string keyWords, PortalTemplateInfo template, string homeDirectory, string portalAlias, string serverPath, string childPath, bool isChildPortal) + [DnnDeprecated(9, 11, 1, "Use DotNetNuke.Entities.Portals.Templates.PortalTemplateInfo instead")] + public partial int CreatePortal(string portalName, UserInfo adminUser, string description, string keyWords, PortalTemplateInfo template, string homeDirectory, string portalAlias, string serverPath, string childPath, bool isChildPortal) { return this.CreatePortal(portalName, adminUser, description, keyWords, template.ToNewPortalTemplateInfo(), homeDirectory, portalAlias, serverPath, childPath, isChildPortal); } - [Obsolete("Deprecated in DNN 9.11.1. Use DotNetNuke.Entities.Portals.Templates.PortalTemplateInfo instead. Scheduled removal in v11.0.0.")] - public int CreatePortal(string portalName, int adminUserId, string description, string keyWords, PortalTemplateInfo template, string homeDirectory, string portalAlias, string serverPath, string childPath, bool isChildPortal) + [DnnDeprecated(9, 11, 1, "Use DotNetNuke.Entities.Portals.Templates.PortalTemplateInfo instead")] + public partial int CreatePortal(string portalName, int adminUserId, string description, string keyWords, PortalTemplateInfo template, string homeDirectory, string portalAlias, string serverPath, string childPath, bool isChildPortal) { return this.CreatePortal(portalName, adminUserId, description, keyWords, template.ToNewPortalTemplateInfo(), homeDirectory, portalAlias, serverPath, childPath, isChildPortal); } @@ -2300,8 +2301,8 @@ private void UpdatePortalInternal(PortalInfo portal, bool clearCache) } } - [Obsolete("Deprecated in DNN 9.11.1. Use DotNetNuke.Entities.Portals.Templates.PortalTemplateInfo instead. Scheduled removal in v11.0.0.")] - public class PortalTemplateInfo + [DnnDeprecated(9, 11, 1, "Use DotNetNuke.Entities.Portals.Templates.PortalTemplateInfo instead")] + public partial class PortalTemplateInfo { private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(PortalController)); private string resourceFilePath; diff --git a/DNN Platform/Library/Entities/Portals/PortalInfo.cs b/DNN Platform/Library/Entities/Portals/PortalInfo.cs index 15741353511..cb558be0ed6 100644 --- a/DNN Platform/Library/Entities/Portals/PortalInfo.cs +++ b/DNN Platform/Library/Entities/Portals/PortalInfo.cs @@ -128,7 +128,7 @@ public string HomeSystemDirectoryMapPath /// Gets or sets image (bitmap) file that is used as background for the portal. /// Name of the file that is used as background. - [Obsolete("Deprecated in 9.7.2. Scheduled for removal in v11.0.0.")] + [Obsolete("Deprecated in DotNetNuke 9.7.2. No replacement. Scheduled removal in v11.0.0.")] [XmlElement("backgroundfile")] public string BackgroundFile { get; set; } @@ -138,7 +138,7 @@ public string HomeSystemDirectoryMapPath /// Gets or sets setting for the type of banner advertising in the portal. /// Type of banner advertising. - [Obsolete("Deprecated in 9.7.2. Scheduled for removal in v11.0.0.")] + [Obsolete("Deprecated in DotNetNuke 9.7.2. No replacement. Scheduled removal in v11.0.0.")] [XmlElement("banneradvertising")] public int BannerAdvertising { get; set; } @@ -148,7 +148,7 @@ public string HomeSystemDirectoryMapPath /// Gets or sets currency format that is used in the portal. /// Currency of the portal. - [Obsolete("Deprecated in 9.7.2. Scheduled for removal in v11.0.0.")] + [Obsolete("Deprecated in DotNetNuke 9.7.2. No replacement. Scheduled removal in v11.0.0.")] [XmlElement("currency")] public string Currency { get; set; } @@ -179,7 +179,7 @@ public string HomeSystemDirectoryMapPath /// Gets or sets amount of currency that is used as a hosting fee of the portal. /// Currency amount hosting fee. - [Obsolete("Deprecated in 9.7.2. Scheduled for removal in v11.0.0.")] + [Obsolete("Deprecated in DotNetNuke 9.7.2. No replacement. Scheduled removal in v11.0.0.")] [XmlElement("hostfee")] public float HostFee { get; set; } @@ -205,7 +205,7 @@ public string HomeSystemDirectoryMapPath /// Gets or sets name of the Payment processor that is used for portal payments, e.g. PayPal. /// Name of the portal payment processor. - [Obsolete("Deprecated in 9.7.2. Scheduled for removal in v11.0.0.")] + [Obsolete("Deprecated in DotNetNuke 9.7.2. No replacement. Scheduled removal in v11.0.0.")] [XmlElement("paymentprocessor")] public string PaymentProcessor { get; set; } @@ -213,7 +213,7 @@ public string HomeSystemDirectoryMapPath [XmlElement("portalid")] int IPortalInfo.PortalId { get; set; } - [Obsolete("Deprecated in 9.7.2. Scheduled for removal in v11.0.0, use DotNetNuke.Abstractions.Portals.IPortalInfo.PortalId instead.")] + [Obsolete("Deprecated in DotNetNuke 9.7.2. Use DotNetNuke.Abstractions.Portals.IPortalInfo.PortalId instead. Scheduled removal in v11.0.0.")] public int PortalID { get => this.ThisAsInterface.PortalId; @@ -234,7 +234,7 @@ public PortalPermissionCollection PortalPermissions /// int IPortalInfo.PortalGroupId { get; set; } - [Obsolete("Deprecated in 9.7.2. Scheduled for removal in v11.0.0, use DotNetNuke.Abstractions.Portals.IPortalInfo.PortalGroupId instead.")] + [Obsolete("Deprecated in DotNetNuke 9.7.2. Use DotNetNuke.Abstractions.Portals.IPortalInfo.PortalGroupId instead. Scheduled removal in v11.0.0.")] public int PortalGroupID { get => this.ThisAsInterface.PortalGroupId; @@ -247,7 +247,7 @@ public int PortalGroupID /// Gets or sets password to use in the payment processor. /// Payment Processor password. - [Obsolete("Deprecated in 9.7.2. Scheduled for removal in v11.0.0.")] + [Obsolete("Deprecated in DotNetNuke 9.7.2. No replacement. Scheduled removal in v11.0.0.")] [XmlElement("processorpassword")] public string ProcessorPassword { get; set; } @@ -255,7 +255,7 @@ public int PortalGroupID /// /// Payment Processor userId. /// - [Obsolete("Deprecated in 9.7.2. Scheduled for removal in v11.0.0.")] + [Obsolete("Deprecated in DotNetNuke 9.7.2. No replacement. Scheduled removal in v11.0.0.")] [XmlElement("processoruserid")] public string ProcessorUserId { get; set; } @@ -288,7 +288,7 @@ public int PortalGroupID public int PrivacyTabId { get; set; } [XmlElement("siteloghistory")] - [Obsolete("Deprecated in 8.0.0. Scheduled removal in v11.0.0.")] + [Obsolete("Deprecated in DotNetNuke 8.0.0. No replacement. Scheduled removal in v11.0.0.")] public int SiteLogHistory { get; set; } /// @@ -313,7 +313,7 @@ public int PortalGroupID /// Gets or sets actual number of actual users for this portal. /// Number of users for the portal. - [Obsolete("Deprecated in 9.7.2. Scheduled for removal in v11.0.0.")] + [Obsolete("Deprecated in DotNetNuke 9.7.2. No replacement. Scheduled removal in v11.0.0.")] [XmlElement("users")] public int Users { @@ -335,7 +335,7 @@ public int Users /// Gets or sets dNN Version # of the portal installation. /// Version # of the portal installation. - [Obsolete("Deprecated in 9.7.2. Scheduled for removal in v11.0.0.")] + [Obsolete("Deprecated in DotNetNuke 9.7.2. No replacement. Scheduled removal in v11.0.0.")] [XmlElement("version")] public string Version { get; set; } @@ -366,7 +366,7 @@ public string AdministratorRoleName /// Gets or sets actual number of pages of the portal. /// Number of pages of the portal. - [Obsolete("Deprecated in 9.7.2. Scheduled for removal in v11.0.0.")] + [Obsolete("Deprecated in DotNetNuke 9.7.2. No replacement. Scheduled removal in v11.0.0.")] [XmlElement("pages")] public int Pages { @@ -413,7 +413,7 @@ public string RegisteredRoleName [XmlIgnore] [JsonIgnore] - [Obsolete("Deprecated in DNN 6.0. Scheduled removal in v10.0.0.")] + [Obsolete("Deprecated in DotNetNuke 6.0.0. No replacement. Scheduled removal in v10.0.0.")] public int TimeZoneOffset { get; set; } /// diff --git a/DNN Platform/Library/Entities/Portals/PortalSettings.cs b/DNN Platform/Library/Entities/Portals/PortalSettings.cs index 9ab34413f1b..00ef27428dd 100644 --- a/DNN Platform/Library/Entities/Portals/PortalSettings.cs +++ b/DNN Platform/Library/Entities/Portals/PortalSettings.cs @@ -191,7 +191,7 @@ public UserInfo UserInfo } /// Gets the mode the user is viewing the page in. - [Obsolete("Deprecated in v9.8.1, use Personalization.GetUserMode() instead, Scheduled for removal in v11.")] + [Obsolete("Deprecated in DotNetNuke 9.8.1. Use Personalization.GetUserMode() instead. Scheduled removal in v11.0.0.")] public Mode UserMode { get => Personalization.GetUserMode(); @@ -383,7 +383,7 @@ public bool DisablePrivateMessage /// public int SearchTabId { get; set; } - [Obsolete("Deprecated in 8.0.0. Scheduled removal in v10.0.0.")] + [Obsolete("Deprecated in DotNetNuke 8.0.0. No replacement. Scheduled removal in v10.0.0.")] public int SiteLogHistory { get; set; } /// @@ -461,7 +461,7 @@ public bool DisablePrivateMessage /// Gets a value indicating whether gets whether to use the module effect in edit mode. /// Defaults to True. - [Obsolete("Deprecated in Platform 7.4.0.. Scheduled removal in v10.0.0.")] + [Obsolete("Deprecated in DotNetNuke 7.4.0. No replacement. Scheduled removal in v10.0.0.")] public bool EnableModuleEffect { get; internal set; } /// @@ -471,8 +471,7 @@ public bool DisablePrivateMessage public bool EnableRegisterNotification { get; internal set; } /// - [Obsolete("This setting is no longer relevant as skin widgets are no longer supported. Scheduled for removal in v11.0.0.")] - + [Obsolete("Deprecated in DotNetNuke 9.8.1. This setting is no longer relevant as skin widgets are no longer supported. Scheduled removal in v11.0.0.")] public bool EnableSkinWidgets { get; internal set; } /// diff --git a/DNN Platform/Library/Entities/Portals/Templates/IPortalTemplateIO.cs b/DNN Platform/Library/Entities/Portals/Templates/IPortalTemplateIO.cs index 4e4ab5c0b44..fcab6d9b89d 100644 --- a/DNN Platform/Library/Entities/Portals/Templates/IPortalTemplateIO.cs +++ b/DNN Platform/Library/Entities/Portals/Templates/IPortalTemplateIO.cs @@ -4,12 +4,13 @@ namespace DotNetNuke.Entities.Portals.Internal { - using System; using System.Collections.Generic; - using System.IO; + using System.IO; - [Obsolete("Scheduled to become internal in v11.0.0.")] - public interface IPortalTemplateIO + using DotNetNuke.Internal.SourceGenerators; + + [DnnDeprecated(9, 11, 1, "No replacement")] + public partial interface IPortalTemplateIO { IEnumerable EnumerateTemplates(); diff --git a/DNN Platform/Library/Entities/Portals/Templates/PortalTemplateIO.cs b/DNN Platform/Library/Entities/Portals/Templates/PortalTemplateIO.cs index d86be534e9e..2713052b90a 100644 --- a/DNN Platform/Library/Entities/Portals/Templates/PortalTemplateIO.cs +++ b/DNN Platform/Library/Entities/Portals/Templates/PortalTemplateIO.cs @@ -9,13 +9,14 @@ namespace DotNetNuke.Entities.Portals.Internal using System.IO; using System.Linq; using System.Xml; - + using DotNetNuke.Common; using DotNetNuke.Common.Utilities.Internal; using DotNetNuke.Framework; + using DotNetNuke.Internal.SourceGenerators; - [Obsolete("Scheduled to become internal in v11.0.0.")] - public class PortalTemplateIO : ServiceLocator, IPortalTemplateIO + [DnnDeprecated(9, 11, 1, "No replacement")] + public partial class PortalTemplateIO : ServiceLocator, IPortalTemplateIO { /// public IEnumerable EnumerateTemplates() diff --git a/DNN Platform/Library/Entities/Profile/ProfileController.cs b/DNN Platform/Library/Entities/Profile/ProfileController.cs index c908b288848..f6526542006 100644 --- a/DNN Platform/Library/Entities/Profile/ProfileController.cs +++ b/DNN Platform/Library/Entities/Profile/ProfileController.cs @@ -13,6 +13,7 @@ namespace DotNetNuke.Entities.Profile using DotNetNuke.Entities.Portals; using DotNetNuke.Entities.Users; using DotNetNuke.Instrumentation; + using DotNetNuke.Internal.SourceGenerators; using DotNetNuke.Security.Profile; using DotNetNuke.Services.Exceptions; using DotNetNuke.Services.FileSystem; @@ -25,7 +26,7 @@ namespace DotNetNuke.Entities.Profile /// The ProfileController class provides Business Layer methods for profiles and /// for profile property Definitions. /// - public class ProfileController + public partial class ProfileController { private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(ProfileController)); private static readonly DataProvider DataProvider = DataProvider.Instance(); @@ -404,8 +405,8 @@ public static List SearchProfilePropertyValues(int portalId, string prop return res; } - [Obsolete("This method has been deprecated. Please use GetPropertyDefinition(ByVal definitionId As Integer, ByVal portalId As Integer) instead. Scheduled removal in v11.0.0.")] - public static ProfilePropertyDefinition GetPropertyDefinition(int definitionId) + [DnnDeprecated(7, 0, 0, "Please use GetPropertyDefinition(int definitionId, int portalId) instead", RemovalVersion = 11)] + public static partial ProfilePropertyDefinition GetPropertyDefinition(int definitionId) { return CBO.FillObject(DataProvider.GetPropertyDefinition(definitionId)); } diff --git a/DNN Platform/Library/Entities/Profile/ProfilePropertyDefinition.cs b/DNN Platform/Library/Entities/Profile/ProfilePropertyDefinition.cs index 706ae102df2..666c416c579 100644 --- a/DNN Platform/Library/Entities/Profile/ProfilePropertyDefinition.cs +++ b/DNN Platform/Library/Entities/Profile/ProfilePropertyDefinition.cs @@ -420,7 +420,7 @@ public ProfileVisibility ProfileVisibility } } - [Obsolete("Deprecated in 6.2 as profile visibility has been extended, keep for compatible with upgrade.. Scheduled removal in v10.0.0.")] + [Obsolete("Deprecated in DotNetNuke 6.2.0. Use ProfileVisibility. Scheduled removal in v10.0.0.")] [Browsable(false)] [XmlIgnore] [JsonIgnore] diff --git a/DNN Platform/Library/Entities/Tabs/ITabController.cs b/DNN Platform/Library/Entities/Tabs/ITabController.cs index a9368345e1f..f7606469339 100644 --- a/DNN Platform/Library/Entities/Tabs/ITabController.cs +++ b/DNN Platform/Library/Entities/Tabs/ITabController.cs @@ -20,7 +20,7 @@ public interface ITabController /// Adds localized copies of the page in all missing languages. /// /// - [Obsolete("This has been deprecated in favor of AddMissingLanguagesWithWarnings. Scheduled for removal in v11.0.0")] + [Obsolete("Deprecated in DotNetNuke 9.11.1. Use AddMissingLanguagesWithWarnings. Scheduled removal in v11.0.0.")] void AddMissingLanguages(int portalId, int tabId); /// Adds localized copies of the page in all missing languages. diff --git a/DNN Platform/Library/Entities/Tabs/TabController.cs b/DNN Platform/Library/Entities/Tabs/TabController.cs index 2c195840b6e..32890c9e89d 100644 --- a/DNN Platform/Library/Entities/Tabs/TabController.cs +++ b/DNN Platform/Library/Entities/Tabs/TabController.cs @@ -28,6 +28,7 @@ namespace DotNetNuke.Entities.Tabs using DotNetNuke.Entities.Users; using DotNetNuke.Framework; using DotNetNuke.Instrumentation; + using DotNetNuke.Internal.SourceGenerators; using DotNetNuke.Security.Permissions; using DotNetNuke.Security.Roles; using DotNetNuke.Services.Exceptions; @@ -969,8 +970,8 @@ public static bool IsValidTabName(string tabName, out string invalidType) /// Adds localized copies of the page in all missing languages. /// /// - [Obsolete("This has been deprecated in favor of AddMissingLanguagesWithWarnings. Scheduled for removal in v11.0.0")] - public void AddMissingLanguages(int portalId, int tabId) + [DnnDeprecated(9, 11, 1, "Use AddMissingLanguagesWithWarnings")] + public partial void AddMissingLanguages(int portalId, int tabId) { this.AddMissingLanguagesWithWarnings(portalId, tabId); } diff --git a/DNN Platform/Library/Entities/Tabs/TabInfo.cs b/DNN Platform/Library/Entities/Tabs/TabInfo.cs index 64749f90c5b..9e5b6d58248 100644 --- a/DNN Platform/Library/Entities/Tabs/TabInfo.cs +++ b/DNN Platform/Library/Entities/Tabs/TabInfo.cs @@ -409,7 +409,7 @@ public string FullUrl } /// Gets a value indicating whether the tab permissions are specified. - [Obsolete("Deprecated in DNN 9.7.0, as this provides no use and always returns false. Scheduled removal in v11.0.0.")] + [Obsolete("Deprecated in DotNetNuke 9.7.0. No replacement. Scheduled removal in v11.0.0.")] [XmlIgnore] [JsonIgnore] public bool TabPermissionsSpecified diff --git a/DNN Platform/Library/Entities/Urls/BrowserTypes.cs b/DNN Platform/Library/Entities/Urls/BrowserTypes.cs index 29eaf4aed15..ceddcc15f5d 100644 --- a/DNN Platform/Library/Entities/Urls/BrowserTypes.cs +++ b/DNN Platform/Library/Entities/Urls/BrowserTypes.cs @@ -6,7 +6,7 @@ namespace DotNetNuke.Entities.Urls { using System; - [Obsolete("Deprecated in 9.7.2. Scheduled for removal in v11.0.0, use DotNetNuke.Abstractions.Urls.BrowserTypes instead.")] + [Obsolete("Deprecated in DotNetNuke 9.7.2. Use DotNetNuke.Abstractions.Urls.BrowserTypes instead. Scheduled removal in v11.0.0.")] public enum BrowserTypes { Normal = 0, diff --git a/DNN Platform/Library/Entities/Users/Membership/UserMembership.cs b/DNN Platform/Library/Entities/Users/Membership/UserMembership.cs index 1f0b52df7a7..5082f5c20f5 100644 --- a/DNN Platform/Library/Entities/Users/Membership/UserMembership.cs +++ b/DNN Platform/Library/Entities/Users/Membership/UserMembership.cs @@ -58,7 +58,7 @@ public bool Approved public bool IsDeleted { get; set; } /// Gets or sets a value indicating whether the User Is Online. - [Obsolete("Support for users online was removed in 8.x, other solutions exist outside of the DNN Platform. Scheduled removal in v11.0.0.")] + [Obsolete("Deprecated in DotNetNuke 8.0.0. Other solutions exist outside of the DNN Platform. Scheduled for removal in v11.0.0.")] public bool IsOnLine { get; set; } /// Gets or sets the Last Activity Date of the User. diff --git a/DNN Platform/Library/Entities/Users/Profile/ProfilePropertyAccess.cs b/DNN Platform/Library/Entities/Users/Profile/ProfilePropertyAccess.cs index c99ebf247bc..82e2ed619b7 100644 --- a/DNN Platform/Library/Entities/Users/Profile/ProfilePropertyAccess.cs +++ b/DNN Platform/Library/Entities/Users/Profile/ProfilePropertyAccess.cs @@ -22,11 +22,12 @@ namespace DotNetNuke.Entities.Users using DotNetNuke.Entities.Profile; using DotNetNuke.Entities.Tabs; using DotNetNuke.Entities.Users.Social; + using DotNetNuke.Internal.SourceGenerators; using DotNetNuke.Security; using DotNetNuke.Services.Tokens; /// Provides access to profile properties. - public class ProfilePropertyAccess : IPropertyAccess + public partial class ProfilePropertyAccess : IPropertyAccess { private readonly UserInfo user; @@ -52,8 +53,8 @@ public CacheLevel Cacheability /// The accessing user. /// The target user. /// true if property accessible, otherwise false. - [Obsolete("Deprecated in 9.8, Use the overload that takes IPortalSettings instead. Scheduled removal in v11.0.0")] - public static bool CheckAccessLevel(PortalSettings portalSettings, ProfilePropertyDefinition property, UserInfo accessingUser, UserInfo targetUser) + [DnnDeprecated(9, 8, 0, "Use the overload that takes IPortalSettings instead")] + public static partial bool CheckAccessLevel(PortalSettings portalSettings, ProfilePropertyDefinition property, UserInfo accessingUser, UserInfo targetUser) { var portalSettingsAsInterface = (IPortalSettings)portalSettings; return CheckAccessLevel(portalSettingsAsInterface, property, accessingUser, targetUser); diff --git a/DNN Platform/Library/Entities/Users/Profile/UserProfile.cs b/DNN Platform/Library/Entities/Users/Profile/UserProfile.cs index 600252bdb3d..20b585d9a2d 100644 --- a/DNN Platform/Library/Entities/Users/Profile/UserProfile.cs +++ b/DNN Platform/Library/Entities/Users/Profile/UserProfile.cs @@ -27,51 +27,51 @@ public class UserProfile : IIndexable #pragma warning disable SA1310 // Field names should not contain underscore #pragma warning disable SA1600 // Elements should be documented // Name properties - [Obsolete("Deprectated in v9.8. Use the properties on this class instead. Scheduled removal in v11.0.0")] + [Obsolete("Deprecated in DotNetNuke 9.8.0. Use the properties on this class instead. Scheduled for removal in v11.0.0.")] public const string USERPROFILE_FirstName = UserProfileFirstName; - [Obsolete("Deprectated in v9.8. Use the properties on this class instead. Scheduled removal in v11.0.0")] + [Obsolete("Deprecated in DotNetNuke 9.8.0. Use the properties on this class instead. Scheduled for removal in v11.0.0.")] public const string USERPROFILE_LastName = UserProfileLastName; - [Obsolete("Deprectated in v9.8. Use the properties on this class instead. Scheduled removal in v11.0.0")] + [Obsolete("Deprecated in DotNetNuke 9.8.0. Use the properties on this class instead. Scheduled for removal in v11.0.0.")] public const string USERPROFILE_Title = UserProfileTitle; // Address Properties - [Obsolete("Deprectated in v9.8. Use the properties on this class instead. Scheduled removal in v11.0.0")] + [Obsolete("Deprecated in DotNetNuke 9.8.0. Use the properties on this class instead. Scheduled for removal in v11.0.0.")] public const string USERPROFILE_Unit = UserProfileUnit; - [Obsolete("Deprectated in v9.8. Use the properties on this class instead. Scheduled removal in v11.0.0")] + [Obsolete("Deprecated in DotNetNuke 9.8.0. Use the properties on this class instead. Scheduled for removal in v11.0.0.")] public const string USERPROFILE_Street = UserProfileStreet; - [Obsolete("Deprectated in v9.8. Use the properties on this class instead. Scheduled removal in v11.0.0")] + [Obsolete("Deprecated in DotNetNuke 9.8.0. Use the properties on this class instead. Scheduled for removal in v11.0.0.")] public const string USERPROFILE_City = UserProfileCity; - [Obsolete("Deprectated in v9.8. Use the properties on this class instead. Scheduled removal in v11.0.0")] + [Obsolete("Deprecated in DotNetNuke 9.8.0. Use the properties on this class instead. Scheduled for removal in v11.0.0.")] public const string USERPROFILE_Country = UserProfileCountry; - [Obsolete("Deprectated in v9.8. Use the properties on this class instead. Scheduled removal in v11.0.0")] + [Obsolete("Deprecated in DotNetNuke 9.8.0. Use the properties on this class instead. Scheduled for removal in v11.0.0.")] public const string USERPROFILE_Region = UserProfileRegion; - [Obsolete("Deprectated in v9.8. Use the properties on this class instead. Scheduled removal in v11.0.0")] + [Obsolete("Deprecated in DotNetNuke 9.8.0. Use the properties on this class instead. Scheduled for removal in v11.0.0.")] public const string USERPROFILE_PostalCode = UserProfilePostalCode; // Phone contact - [Obsolete("Deprectated in v9.8. Use the properties on this class instead. Scheduled removal in v11.0.0")] + [Obsolete("Deprecated in DotNetNuke 9.8.0. Use the properties on this class instead. Scheduled for removal in v11.0.0.")] public const string USERPROFILE_Telephone = UserProfileTelephone; - [Obsolete("Deprectated in v9.8. Use the properties on this class instead. Scheduled removal in v11.0.0")] + [Obsolete("Deprecated in DotNetNuke 9.8.0. Use the properties on this class instead. Scheduled for removal in v11.0.0.")] public const string USERPROFILE_Cell = UserProfileCell; - [Obsolete("Deprectated in v9.8. Use the properties on this class instead. Scheduled removal in v11.0.0")] + [Obsolete("Deprecated in DotNetNuke 9.8.0. Use the properties on this class instead. Scheduled for removal in v11.0.0.")] public const string USERPROFILE_Fax = UserProfileFax; // Online contact - [Obsolete("Deprectated in v9.8. Use the properties on this class instead. Scheduled removal in v11.0.0")] + [Obsolete("Deprecated in DotNetNuke 9.8.0. Use the properties on this class instead. Scheduled for removal in v11.0.0.")] public const string USERPROFILE_Website = UserProfileWebsite; - [Obsolete("Deprectated in v9.8. Use the properties on this class instead. Scheduled removal in v11.0.0")] + [Obsolete("Deprecated in DotNetNuke 9.8.0. Use the properties on this class instead. Scheduled for removal in v11.0.0.")] public const string USERPROFILE_IM = UserProfileIM; // Preferences - [Obsolete("Deprectated in v9.8. Use the properties on this class instead. Scheduled removal in v11.0.0")] + [Obsolete("Deprecated in DotNetNuke 9.8.0. Use the properties on this class instead. Scheduled for removal in v11.0.0.")] public const string USERPROFILE_Photo = UserProfilePhoto; - [Obsolete("Deprectated in v9.8. Use the properties on this class instead. Scheduled removal in v11.0.0")] + [Obsolete("Deprecated in DotNetNuke 9.8.0. Use the properties on this class instead. Scheduled for removal in v11.0.0.")] public const string USERPROFILE_TimeZone = UserProfileTimeZone; - [Obsolete("Deprectated in v9.8. Use the properties on this class instead. Scheduled removal in v11.0.0")] + [Obsolete("Deprecated in DotNetNuke 9.8.0. Use the properties on this class instead. Scheduled for removal in v11.0.0.")] public const string USERPROFILE_PreferredLocale = UserProfilePreferredLocale; - [Obsolete("Deprectated in v9.8. Use the properties on this class instead. Scheduled removal in v11.0.0")] + [Obsolete("Deprecated in DotNetNuke 9.8.0. Use the properties on this class instead. Scheduled for removal in v11.0.0.")] public const string USERPROFILE_PreferredTimeZone = UserProfilePreferredTimeZone; - [Obsolete("Deprectated in v9.8. Use the properties on this class instead. Scheduled removal in v11.0.0")] + [Obsolete("Deprecated in DotNetNuke 9.8.0. Use the properties on this class instead. Scheduled for removal in v11.0.0.")] public const string USERPROFILE_Biography = UserProfileBiography; #pragma warning restore SA1310 // Field names should not contain underscore #pragma warning restore SA1600 // Elements should be documented @@ -168,7 +168,7 @@ public string PhotoURL } /// Gets the file path of the photo url (designed to be used when files are loaded via the filesystem e.g for caching). - [Obsolete("Obsolete in 7.2.2, Use PhotoUrl instead of it.. Scheduled removal in v10.0.0.")] + [Obsolete("Deprecated in DotNetNuke 7.2.2. Use PhotoUrl instead. Scheduled for removal in v10.0.0.")] public string PhotoURLFile { get diff --git a/DNN Platform/Library/Entities/Users/UserController.cs b/DNN Platform/Library/Entities/Users/UserController.cs index f0397f4b2e7..2f9f2125073 100644 --- a/DNN Platform/Library/Entities/Users/UserController.cs +++ b/DNN Platform/Library/Entities/Users/UserController.cs @@ -24,6 +24,7 @@ namespace DotNetNuke.Entities.Users using DotNetNuke.Entities.Profile; using DotNetNuke.Entities.Users.Membership; using DotNetNuke.Framework; + using DotNetNuke.Internal.SourceGenerators; using DotNetNuke.Security; using DotNetNuke.Security.Membership; using DotNetNuke.Security.Permissions; @@ -326,8 +327,8 @@ public static void ChangeUsername(int userId, string newUsername) /// or /// . /// - [Obsolete("Deprecated in 9.8.1. Scheduled removal in v11.0.0. No alternative method implemented.")] - public static void CheckInsecurePassword(string username, string password, ref UserLoginStatus loginStatus) + [DnnDeprecated(9, 8, 1, "No alternative method implemented")] + public static partial void CheckInsecurePassword(string username, string password, ref UserLoginStatus loginStatus) { if (username == "admin" && (password == "admin" || password == "dnnadmin")) { @@ -567,8 +568,8 @@ public static ArrayList GetDeletedUsers(int portalId) /// Gets a collection of Online Users. /// The Id of the Portal. /// An ArrayList of UserInfo objects. - [Obsolete("Support for users online was removed in 8.x, other solutions exist outside of the DNN Platform. Scheduled removal in v11.0.0.")] - public static ArrayList GetOnlineUsers(int portalId) + [DnnDeprecated(8, 0, 0, "Other solutions exist outside of the DNN Platform", RemovalVersion = 11)] + public static partial ArrayList GetOnlineUsers(int portalId) { return MembershipProvider.Instance().GetOnlineUsers(GetEffectivePortalId(portalId)); } diff --git a/DNN Platform/Library/Entities/Users/Users Online/AnonymousUserInfo.cs b/DNN Platform/Library/Entities/Users/Users Online/AnonymousUserInfo.cs index 0823778327b..e3938e60574 100644 --- a/DNN Platform/Library/Entities/Users/Users Online/AnonymousUserInfo.cs +++ b/DNN Platform/Library/Entities/Users/Users Online/AnonymousUserInfo.cs @@ -5,17 +5,18 @@ namespace DotNetNuke.Entities.Users { using System; + using DotNetNuke.Internal.SourceGenerators; + /// Project: DotNetNuke /// Namespace: DotNetNuke.Entities.Users /// The AnonymousUserInfo class provides an Entity for an anonymous user. [Serializable] - [Obsolete("Support for users online was removed in 8.x, other solutions exist outside of the DNN Platform. Scheduled removal in v11.0.0.")] - public class AnonymousUserInfo : BaseUserInfo + [DnnDeprecated(8, 0, 0, "Other solutions exist outside of the DNN Platform", RemovalVersion = 11)] + public partial class AnonymousUserInfo : BaseUserInfo { private string userID; /// Gets or sets the User Id for this online user. - [Obsolete("Support for users online was removed in 8.x, other solutions exist outside of the DNN Platform. Scheduled removal in v11.0.0.")] public string UserID { get diff --git a/DNN Platform/Library/Entities/Users/Users Online/BaseUserInfo.cs b/DNN Platform/Library/Entities/Users/Users Online/BaseUserInfo.cs index 9a26bb1db75..2c28db1c2b9 100644 --- a/DNN Platform/Library/Entities/Users/Users Online/BaseUserInfo.cs +++ b/DNN Platform/Library/Entities/Users/Users Online/BaseUserInfo.cs @@ -4,14 +4,16 @@ namespace DotNetNuke.Entities.Users { using System; - + + using DotNetNuke.Internal.SourceGenerators; + /// Project: DotNetNuke /// Namespace: DotNetNuke.Entities.Users /// Class: BaseUserInfo /// The BaseUserInfo class provides a base Entity for an online user. [Serializable] - [Obsolete("Support for users online was removed in 8.x, other solutions exist outside of the DNN Platform. Scheduled removal in v11.0.0.")] - public abstract class BaseUserInfo + [DnnDeprecated(8, 0, 0, "Other solutions exist outside of the DNN Platform", RemovalVersion = 11)] + public abstract partial class BaseUserInfo { private DateTime creationDate; private DateTime lastActiveDate; @@ -19,7 +21,6 @@ public abstract class BaseUserInfo private int tabID; /// Gets or sets the PortalId for this online user. - [Obsolete("Support for users online was removed in 8.x, other solutions exist outside of the DNN Platform. Scheduled removal in v11.0.0.")] public int PortalID { get @@ -34,7 +35,6 @@ public int PortalID } /// Gets or sets the TabId for this online user. - [Obsolete("Support for users online was removed in 8.x, other solutions exist outside of the DNN Platform. Scheduled removal in v11.0.0.")] public int TabID { get @@ -49,7 +49,6 @@ public int TabID } /// Gets or sets the CreationDate for this online user. - [Obsolete("Support for users online was removed in 8.x, other solutions exist outside of the DNN Platform. Scheduled removal in v11.0.0.")] public DateTime CreationDate { get @@ -64,7 +63,6 @@ public DateTime CreationDate } /// Gets or sets the LastActiveDate for this online user. - [Obsolete("Support for users online was removed in 8.x, other solutions exist outside of the DNN Platform. Scheduled removal in v11.0.0.")] public DateTime LastActiveDate { get diff --git a/DNN Platform/Library/Entities/Users/Users Online/OnlineUserInfo.cs b/DNN Platform/Library/Entities/Users/Users Online/OnlineUserInfo.cs index 948d1478549..803eada7e32 100644 --- a/DNN Platform/Library/Entities/Users/Users Online/OnlineUserInfo.cs +++ b/DNN Platform/Library/Entities/Users/Users Online/OnlineUserInfo.cs @@ -4,19 +4,20 @@ namespace DotNetNuke.Entities.Users { using System; - + + using DotNetNuke.Internal.SourceGenerators; + /// Project: DotNetNuke /// Namespace: DotNetNuke.Entities.Users /// Class: OnlineUserInfo /// The OnlineUserInfo class provides an Entity for an online user. [Serializable] - [Obsolete("Support for users online was removed in 8.x, other solutions exist outside of the DNN Platform. Scheduled removal in v11.0.0.")] - public class OnlineUserInfo : BaseUserInfo + [DnnDeprecated(8, 0, 0, "Other solutions exist outside of the DNN Platform", RemovalVersion = 11)] + public partial class OnlineUserInfo : BaseUserInfo { private int userID; /// Gets or sets the User Id for this online user. - [Obsolete("Support for users online was removed in 8.x, other solutions exist outside of the DNN Platform. Scheduled removal in v11.0.0.")] public int UserID { get diff --git a/DNN Platform/Library/Entities/Users/Users Online/PurgeUsersOnline.cs b/DNN Platform/Library/Entities/Users/Users Online/PurgeUsersOnline.cs index 7c5c1eed225..f2ca2102380 100644 --- a/DNN Platform/Library/Entities/Users/Users Online/PurgeUsersOnline.cs +++ b/DNN Platform/Library/Entities/Users/Users Online/PurgeUsersOnline.cs @@ -5,6 +5,7 @@ namespace DotNetNuke.Entities.Users { using System; + using DotNetNuke.Internal.SourceGenerators; using DotNetNuke.Services.Exceptions; using DotNetNuke.Services.Scheduling; @@ -15,22 +16,20 @@ namespace DotNetNuke.Entities.Users /// The PurgeUsersOnline class provides a Scheduler for purging the Users Online /// data. /// - [Obsolete("Support for users online was removed in 8.x, other solutions exist outside of the DNN Platform. Scheduled removal in v11.0.0.")] - public class PurgeUsersOnline : SchedulerClient + [DnnDeprecated(8, 0, 0, "Other solutions exist outside of the DNN Platform", RemovalVersion = 10)] + public partial class PurgeUsersOnline : SchedulerClient { /// /// Initializes a new instance of the class. /// Constructs a PurgeUsesOnline SchedulerClient. /// /// A SchedulerHistiryItem. - [Obsolete("Support for users online was removed in 8.x, other solutions exist outside of the DNN Platform. Scheduled removal in v11.0.0.")] public PurgeUsersOnline(ScheduleHistoryItem objScheduleHistoryItem) { this.ScheduleHistoryItem = objScheduleHistoryItem; } /// DoWork does th4 Scheduler work. - [Obsolete("Support for users online was removed in 8.x, other solutions exist outside of the DNN Platform. Scheduled removal in v11.0.0.")] public override void DoWork() { try @@ -55,7 +54,6 @@ public override void DoWork() } /// UpdateUsersOnline updates the Users Online information. - [Obsolete("Support for users online was removed in 8.x, other solutions exist outside of the DNN Platform. Scheduled removal in v11.0.0.")] private void UpdateUsersOnline() { var objUserOnlineController = new UserOnlineController(); diff --git a/DNN Platform/Library/Entities/Users/Users Online/UserOnlineController.cs b/DNN Platform/Library/Entities/Users/Users Online/UserOnlineController.cs index 61e93c67694..8e4897550e4 100644 --- a/DNN Platform/Library/Entities/Users/Users Online/UserOnlineController.cs +++ b/DNN Platform/Library/Entities/Users/Users Online/UserOnlineController.cs @@ -11,12 +11,13 @@ namespace DotNetNuke.Entities.Users using DotNetNuke.Common.Utilities; using DotNetNuke.Entities.Portals; using DotNetNuke.Instrumentation; + using DotNetNuke.Internal.SourceGenerators; using MembershipProvider = DotNetNuke.Security.Membership.MembershipProvider; /// The UserOnlineController class provides Business Layer methods for Users Online. - [Obsolete("Support for users online was removed in 8.x, other solutions exist outside of the DNN Platform. Scheduled removal in v11.0.0.")] - public class UserOnlineController + [DnnDeprecated(8, 0, 0, "Other solutions exist outside of the DNN Platform", RemovalVersion = 11)] + public partial class UserOnlineController { private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(UserOnlineController)); private static readonly MembershipProvider MemberProvider = MembershipProvider.Instance(); @@ -24,7 +25,6 @@ public class UserOnlineController private static readonly string CacheKey = "OnlineUserList"; /// Clears the cached Users Online Information. - [Obsolete("Support for users online was removed in 8.x, other solutions exist outside of the DNN Platform. Scheduled removal in v11.0.0.")] public void ClearUserList() { string key = "OnlineUserList"; @@ -33,7 +33,6 @@ public void ClearUserList() /// Gets the Online time window. /// The window to use in minutes when determining if the user is online. - [Obsolete("Support for users online was removed in 8.x, other solutions exist outside of the DNN Platform. Scheduled removal in v11.0.0.")] public int GetOnlineTimeWindow() { return Host.Host.UsersOnlineTimeWindow; @@ -41,7 +40,6 @@ public int GetOnlineTimeWindow() /// Gets the cached Users Online Information. /// A with keys for the user ID (a GUID for anonymous users) and instances for the values. - [Obsolete("Support for users online was removed in 8.x, other solutions exist outside of the DNN Platform. Scheduled removal in v11.0.0.")] public Hashtable GetUserList() { var userList = (Hashtable)DataCache.GetCache(CacheKey); @@ -63,7 +61,6 @@ public Hashtable GetUserList() /// Gets whether the Users Online functionality is enabled. /// if the Users Online functionality is enabled, otherwise . - [Obsolete("Support for users online was removed in 8.x, other solutions exist outside of the DNN Platform. Scheduled removal in v11.0.0.")] public bool IsEnabled() { return Host.Host.EnableUsersOnline; @@ -71,7 +68,6 @@ public bool IsEnabled() /// Determines whether a User is online. /// if the user is online, otherwise . - [Obsolete("Support for users online was removed in 8.x, other solutions exist outside of the DNN Platform. Scheduled removal in v11.0.0.")] public bool IsUserOnline(UserInfo user) { bool isOnline = false; @@ -84,14 +80,12 @@ public bool IsUserOnline(UserInfo user) } /// Sets the cached Users Online Information. - [Obsolete("Support for users online was removed in 8.x, other solutions exist outside of the DNN Platform. Scheduled removal in v11.0.0.")] public void SetUserList(Hashtable userList) { DataCache.SetCache(CacheKey, userList); } /// Tracks an online User. - [Obsolete("Support for users online was removed in 8.x, other solutions exist outside of the DNN Platform. Scheduled removal in v11.0.0.")] public void TrackUsers() { HttpContext context = HttpContext.Current; @@ -117,7 +111,6 @@ public void TrackUsers() } /// Update the Users Online information. - [Obsolete("Support for users online was removed in 8.x, other solutions exist outside of the DNN Platform. Scheduled removal in v11.0.0.")] public void UpdateUsersOnline() { // Get a Current User List @@ -145,7 +138,6 @@ public void UpdateUsersOnline() /// Tracks an Anonymous User. /// An HttpContext Object. - [Obsolete("Support for users online was removed in 8.x, other solutions exist outside of the DNN Platform. Scheduled removal in v11.0.0.")] private void TrackAnonymousUser(HttpContext context) { string cookieName = "DotNetNukeAnonymous"; @@ -231,7 +223,6 @@ private void TrackAnonymousUser(HttpContext context) /// Tracks an Authenticated User. /// An HttpContext Object. - [Obsolete("Support for users online was removed in 8.x, other solutions exist outside of the DNN Platform. Scheduled removal in v11.0.0.")] private void TrackAuthenticatedUser(HttpContext context) { // Retrieve Portal Settings diff --git a/DNN Platform/Library/Framework/JavaScriptLibraries/JavaScript.cs b/DNN Platform/Library/Framework/JavaScriptLibraries/JavaScript.cs index e5ecd1ef33f..5842360266a 100644 --- a/DNN Platform/Library/Framework/JavaScriptLibraries/JavaScript.cs +++ b/DNN Platform/Library/Framework/JavaScriptLibraries/JavaScript.cs @@ -80,15 +80,6 @@ public static void RequestRegistration(string jsname) case CommonJs.jQuery: RequestRegistration(CommonJs.jQueryMigrate); break; - case CommonJs.DnnPlugins: - RequestRegistration(CommonJs.jQueryUI); - RequestRegistration(CommonJs.HoverIntent); - AddPreInstallorLegacyItemRequest(jsname); - return; - case CommonJs.HoverIntent: - case CommonJs.jQueryFileUpload: - AddPreInstallorLegacyItemRequest(jsname); - return; } RequestRegistration(jsname, null, SpecificVersion.Latest); @@ -442,14 +433,6 @@ private static void RegisterScript(Page page, JavaScriptLibrary jsl) ClientResourceManager.RegisterScript(page, GetScriptPath(jsl, page), GetFileOrder(jsl), GetScriptLocation(jsl), jsl.LibraryName, jsl.Version.ToString(3)); - // workaround to support IE specific script until we move to IE version that no longer requires this - if (jsl.LibraryName == CommonJs.jQueryFileUpload) - { - ClientResourceManager.RegisterScript( - page, - "~/Resources/Shared/Scripts/jquery/jquery.iframe-transport.js"); - } - if (Host.CdnEnabled && !string.IsNullOrEmpty(jsl.ObjectName)) { string pagePortion; @@ -558,71 +541,6 @@ where item.ToString().StartsWith(LegacyPrefix) "DnnPageHeaderProvider"); } - break; - case CommonJs.DnnPlugins: - // This method maybe called when Page.Form hasn't initialized yet, in that situation if needed should reference dnn js manually. - // such as call jQuery.RegisterDnnJQueryPlugins in Control.OnInit. - if (page.Form != null) - { - } - - // register dependency - if (GetHighestVersionLibrary(CommonJs.jQuery) == null) - { - ClientResourceManager.RegisterScript( - page, - jQuery.GetJQueryScriptReference(), - FileOrder.Js.jQuery, - "DnnPageHeaderProvider"); - } - - if (GetHighestVersionLibrary(CommonJs.jQueryMigrate) == null) - { - ClientResourceManager.RegisterScript( - page, - jQuery.GetJQueryMigrateScriptReference(), - FileOrder.Js.jQueryMigrate, - "DnnPageHeaderProvider"); - } - - // actual jqueryui - if (GetHighestVersionLibrary(CommonJs.jQueryUI) == null) - { - ClientResourceManager.RegisterScript( - page, - jQuery.GetJQueryUIScriptReference(), - FileOrder.Js.jQueryUI, - "DnnPageHeaderProvider"); - } - - if (GetHighestVersionLibrary(CommonJs.HoverIntent) == null) - { - ClientResourceManager.RegisterScript( - page, - "~/Resources/Shared/Scripts/jquery/jquery.hoverIntent.min.js", - FileOrder.Js.HoverIntent); - } - - // no package for this - CRM will deduplicate - ClientResourceManager.RegisterScript(page, "~/Resources/Shared/Scripts/dnn.jquery.js"); - break; - case CommonJs.jQueryFileUpload: - ClientResourceManager.RegisterScript( - page, - "~/Resources/Shared/Scripts/jquery/jquery.iframe-transport.js"); - ClientResourceManager.RegisterScript( - page, - "~/Resources/Shared/Scripts/jquery/jquery.fileupload.js"); - break; - case CommonJs.HoverIntent: - if (GetHighestVersionLibrary(CommonJs.HoverIntent) == null) - { - ClientResourceManager.RegisterScript( - page, - "~/Resources/Shared/Scripts/jquery/jquery.hoverIntent.min.js", - FileOrder.Js.HoverIntent); - } - break; } } diff --git a/DNN Platform/Library/Framework/Providers/ProviderConfigurationHandler.cs b/DNN Platform/Library/Framework/Providers/ProviderConfigurationHandler.cs index 74e0f45ba15..02e694ad97e 100644 --- a/DNN Platform/Library/Framework/Providers/ProviderConfigurationHandler.cs +++ b/DNN Platform/Library/Framework/Providers/ProviderConfigurationHandler.cs @@ -3,12 +3,13 @@ // See the LICENSE file in the project root for more information namespace DotNetNuke.Framework.Providers { - using System; using System.Configuration; using System.Xml; - - [Obsolete("This class is obsolete. It is no longer used to load provider configurations, as there are medium trust issues. Scheduled removal in v11.0.0.")] - internal class ProviderConfigurationHandler : IConfigurationSectionHandler + + using DotNetNuke.Internal.SourceGenerators; + + [DnnDeprecated(7, 0, 0, "It is no longer used to load provider configurations, as there are medium trust issues", RemovalVersion = 10)] + internal partial class ProviderConfigurationHandler : IConfigurationSectionHandler { /// public virtual object Create(object parent, object context, XmlNode node) diff --git a/DNN Platform/Library/Framework/Reflection.cs b/DNN Platform/Library/Framework/Reflection.cs index 107850a52d0..4b60f1a490c 100644 --- a/DNN Platform/Library/Framework/Reflection.cs +++ b/DNN Platform/Library/Framework/Reflection.cs @@ -11,12 +11,13 @@ namespace DotNetNuke.Framework using DotNetNuke.Common.Utilities; using DotNetNuke.Framework.Providers; using DotNetNuke.Instrumentation; + using DotNetNuke.Internal.SourceGenerators; using DotNetNuke.Services.Exceptions; using Microsoft.Extensions.DependencyInjection; /// Library responsible for reflection. - public class Reflection + public partial class Reflection { private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(Reflection)); @@ -24,8 +25,8 @@ public class Reflection /// The type of Object to create (data/navigation). /// The created Object. /// Overload for creating an object from a Provider configured in web.config. - [Obsolete("Deprecated in DotNetNuke 9.11.3. Please use overload with IServiceProvider. Scheduled removal in v11.0.0.")] - public static object CreateObject(string objectProviderType) + [DnnDeprecated(9, 11, 3, "Please use overload with IServiceProvider")] + public static partial object CreateObject(string objectProviderType) { return CreateObject(objectProviderType, true); } @@ -44,8 +45,8 @@ public static object CreateObject(IServiceProvider serviceProvider, string objec /// Caching switch. /// The created Object. /// Overload for creating an object from a Provider configured in web.config. - [Obsolete("Deprecated in DotNetNuke 9.11.3. Please use overload with IServiceProvider. Scheduled removal in v11.0.0.")] - public static object CreateObject(string objectProviderType, bool useCache) + [DnnDeprecated(9, 11, 3, "Please use overload with IServiceProvider")] + public static partial object CreateObject(string objectProviderType, bool useCache) { return CreateObject(objectProviderType, string.Empty, string.Empty, string.Empty, useCache); } @@ -66,8 +67,8 @@ public static object CreateObject(IServiceProvider serviceProvider, string objec /// The assembly of the object to create. /// The created Object. /// Overload for creating an object from a Provider including NameSpace and AssemblyName ( this allows derived providers to share the same config ). - [Obsolete("Deprecated in DotNetNuke 9.11.3. Please use overload with IServiceProvider. Scheduled removal in v11.0.0.")] - public static object CreateObject(string objectProviderType, string objectNamespace, string objectAssemblyName) + [DnnDeprecated(9, 11, 3, "Please use overload with IServiceProvider")] + public static partial object CreateObject(string objectProviderType, string objectNamespace, string objectAssemblyName) { return CreateObject(objectProviderType, string.Empty, objectNamespace, objectAssemblyName, true); } @@ -90,8 +91,8 @@ public static object CreateObject(IServiceProvider serviceProvider, string objec /// Caching switch. /// The created Object. /// Overload for creating an object from a Provider including NameSpace and AssemblyName ( this allows derived providers to share the same config ). - [Obsolete("Deprecated in DotNetNuke 9.11.3. Please use overload with IServiceProvider. Scheduled removal in v11.0.0.")] - public static object CreateObject(string objectProviderType, string objectNamespace, string objectAssemblyName, bool useCache) + [DnnDeprecated(9, 11, 3, "Please use overload with IServiceProvider")] + public static partial object CreateObject(string objectProviderType, string objectNamespace, string objectAssemblyName, bool useCache) { return CreateObject(objectProviderType, string.Empty, objectNamespace, objectAssemblyName, useCache); } @@ -115,8 +116,8 @@ public static object CreateObject(IServiceProvider serviceProvider, string objec /// The assembly of the object to create. /// The created Object. /// Overload for creating an object from a Provider including NameSpace, AssemblyName and ProviderName. - [Obsolete("Deprecated in DotNetNuke 9.11.3. Please use overload with IServiceProvider. Scheduled removal in v11.0.0.")] - public static object CreateObject(string objectProviderType, string objectProviderName, string objectNamespace, string objectAssemblyName) + [DnnDeprecated(9, 11, 3, "Please use overload with IServiceProvider")] + public static partial object CreateObject(string objectProviderType, string objectProviderName, string objectNamespace, string objectAssemblyName) { return CreateObject(objectProviderType, objectProviderName, objectNamespace, objectAssemblyName, true); } @@ -141,8 +142,8 @@ public static object CreateObject(IServiceProvider serviceProvider, string objec /// Caching switch. /// The created Object. /// Overload for creating an object from a Provider including NameSpace, AssemblyName and ProviderName. - [Obsolete("Deprecated in DotNetNuke 9.11.3. Please use overload with IServiceProvider. Scheduled removal in v11.0.0.")] - public static object CreateObject(string objectProviderType, string objectProviderName, string objectNamespace, string objectAssemblyName, bool useCache) + [DnnDeprecated(9, 11, 3, "Please use overload with IServiceProvider")] + public static partial object CreateObject(string objectProviderType, string objectProviderName, string objectNamespace, string objectAssemblyName, bool useCache) { return CreateObject(objectProviderType, objectProviderName, objectNamespace, objectAssemblyName, useCache, true); } @@ -169,8 +170,8 @@ public static object CreateObject(IServiceProvider serviceProvider, string objec /// Whether append provider name as part of the assembly name. /// The created Object. /// Overload for creating an object from a Provider including NameSpace, AssemblyName and ProviderName. - [Obsolete("Deprecated in DotNetNuke 9.11.3. Please use overload with IServiceProvider. Scheduled removal in v11.0.0.")] - public static object CreateObject( + [DnnDeprecated(9, 11, 3, "Please use overload with IServiceProvider")] + public static partial object CreateObject( string objectProviderType, string objectProviderName, string objectNamespace, @@ -258,8 +259,8 @@ public static object CreateObject(IServiceProvider serviceProvider, string objec /// The Cache Key. /// The created Object. /// Overload that takes a fully-qualified typename and a Cache Key. - [Obsolete("Deprecated in DotNetNuke 9.11.3. Please use overload with IServiceProvider. Scheduled removal in v11.0.0.")] - public static object CreateObject(string typeName, string cacheKey) + [DnnDeprecated(9, 11, 3, "Please use overload with IServiceProvider")] + public static partial object CreateObject(string typeName, string cacheKey) { return CreateObject(typeName, cacheKey, true); } @@ -280,8 +281,8 @@ public static object CreateObject(IServiceProvider serviceProvider, string typeN /// Caching switch. /// The created Object. /// Overload that takes a fully-qualified typename and a Cache Key. - [Obsolete("Deprecated in DotNetNuke 9.11.3. Please use overload with IServiceProvider. Scheduled removal in v11.0.0.")] - public static object CreateObject(string typeName, string cacheKey, bool useCache) + [DnnDeprecated(9, 11, 3, "Please use overload with IServiceProvider")] + public static partial object CreateObject(string typeName, string cacheKey, bool useCache) { return CreateObject(Globals.DependencyProvider, typeName, cacheKey, useCache); } @@ -302,8 +303,8 @@ public static object CreateObject(IServiceProvider serviceProvider, string typeN /// The type of object to create. /// The created object. /// Generic version. - [Obsolete("Deprecated in DotNetNuke 9.11.3. Please use overload with IServiceProvider. Scheduled removal in v11.0.0.")] - public static T CreateObject() + [DnnDeprecated(9, 11, 3, "Please use overload with IServiceProvider")] + public static partial T CreateObject() { return CreateObject(Globals.DependencyProvider); } @@ -328,8 +329,8 @@ public static T CreateObject(IServiceProvider serviceProvider) /// Creates an object. /// The type of object to create. /// The created object. - [Obsolete("Deprecated in DotNetNuke 9.11.3. Please use overload with IServiceProvider. Scheduled removal in v11.0.0.")] - public static object CreateObject(Type type) + [DnnDeprecated(9, 11, 3, "Please use overload with IServiceProvider")] + public static partial object CreateObject(Type type) { return CreateObject(Globals.DependencyProvider, type); } @@ -492,8 +493,8 @@ public static void InvokeMethod(Type type, string propertyName, object target, o } // dynamically create a default Provider from a ProviderType - this method was used by the CachingProvider to avoid a circular dependency - [Obsolete("This method has been deprecated. Please use CreateObject(ByVal ObjectProviderType As String, ByVal UseCache As Boolean) As Object. Scheduled removal in v11.0.0.")] - internal static object CreateObjectNotCached(string objectProviderType) + [DnnDeprecated(7, 0, 0, "Please use CreateObject(string objectProviderType, bool useCache)", RemovalVersion = 11)] + internal static partial object CreateObjectNotCached(string objectProviderType) { string typeName = string.Empty; Type objType = null; diff --git a/DNN Platform/Library/Framework/SecurityPolicy.cs b/DNN Platform/Library/Framework/SecurityPolicy.cs index c2ad0fb1320..e52c74c4de6 100644 --- a/DNN Platform/Library/Framework/SecurityPolicy.cs +++ b/DNN Platform/Library/Framework/SecurityPolicy.cs @@ -9,7 +9,9 @@ namespace DotNetNuke.Framework using System.Security.Permissions; using System.Web; - public class SecurityPolicy + using DotNetNuke.Internal.SourceGenerators; + + public partial class SecurityPolicy { public const string ReflectionPermission = "ReflectionPermission"; public const string WebPermission = "WebPermission"; @@ -122,8 +124,8 @@ public static bool HasPermissions(string permissions, ref string permission) return hasPermission; } - [Obsolete("Replaced by correctly spelt method. Scheduled removal in v10.0.0.")] - public static bool HasRelectionPermission() + [DnnDeprecated(7, 0, 0, "Replaced by correctly spelt method", RemovalVersion = 10)] + public static partial bool HasRelectionPermission() { GetPermissions(); return reflectionPermission; diff --git a/DNN Platform/Library/Framework/jQuery.cs b/DNN Platform/Library/Framework/jQuery.cs index f2c7b2120c7..cbc481095f8 100644 --- a/DNN Platform/Library/Framework/jQuery.cs +++ b/DNN Platform/Library/Framework/jQuery.cs @@ -14,6 +14,7 @@ namespace DotNetNuke.Framework using DotNetNuke.Common.Utilities; using DotNetNuke.Entities.Host; using DotNetNuke.Framework.JavaScriptLibraries; + using DotNetNuke.Internal.SourceGenerators; using DotNetNuke.Services.Exceptions; using DotNetNuke.Services.Localization; @@ -24,7 +25,7 @@ namespace DotNetNuke.Framework [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1300:ElementMustBeginWithUpperCaseLetter", Justification = "Breaking Change")] // ReSharper disable once InconsistentNaming - public class jQuery + public partial class jQuery { /// Returns the default URL for a hosted version of the jQuery script. /// @@ -32,7 +33,7 @@ public class jQuery /// Using the hosted version increases the likelihood that the file is already /// cached in the user's browser. /// - public const string DefaultHostedUrl = "https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"; + public const string DefaultHostedUrl = "https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"; public const string DefaultUIHostedUrl = "https://ajax.googleapis.com/ajax/libs/jqueryui/1.13.2/jquery-ui.min.js"; private const string JQueryDebugFile = "~/Resources/Shared/Scripts/jquery/jquery.js"; @@ -50,7 +51,7 @@ public class jQuery /// Gets the HostSetting for the URL of the hosted version of the jQuery script. /// The HostSetting for the URL of the hosted version of the jQuery script. /// This is a simple wrapper around the Host.jQueryUrl property. - [Obsolete("This is managed through the JavaScript Library package. Scheduled removal in v10.0.0.")] + [Obsolete("Deprecated in DotNetNuke 7.3.1. This is managed through the JavaScript Library package. Scheduled removal in v10.0.0.")] public static string HostedUrl { get @@ -67,7 +68,7 @@ public static string HostedUrl /// Gets the HostSetting for the URL of the hosted version of the jQuery migrated script. /// The HostSetting for the URL of the hosted version of the jQuery migrated script. /// This is a simple wrapper around the Host.jQueryUrl property. - [Obsolete("This is managed through the JavaScript Library package. Scheduled removal in v10.0.0.")] + [Obsolete("Deprecated in DotNetNuke 7.3.1. This is managed through the JavaScript Library package. Scheduled removal in v10.0.0.")] public static string HostedMigrateUrl { get @@ -84,7 +85,7 @@ public static string HostedMigrateUrl /// Gets the HostSetting for the URL of the hosted version of the jQuery UI script. /// The HostSetting for the URL of the hosted version of the jQuery UI script. /// This is a simple wrapper around the Host.jQueryUIUrl property. - [Obsolete("This is managed through the JavaScript Library package. Scheduled removal in v10.0.0.")] + [Obsolete("Deprecated in DotNetNuke 7.3.1. This is managed through the JavaScript Library package. Scheduled removal in v10.0.0.")] public static string HostedUIUrl { get @@ -103,7 +104,7 @@ public static string HostedUIUrl /// This property checks for both the minified version and the full uncompressed version of jQuery. /// These files should exist in the /Resources/Shared/Scripts/jquery directory. /// - [Obsolete("This is managed through the JavaScript Library package. Scheduled removal in v10.0.0.")] + [Obsolete("Deprecated in DotNetNuke 7.3.1. This is managed through the JavaScript Library package. Scheduled removal in v10.0.0.")] public static bool IsInstalled { get @@ -119,7 +120,7 @@ public static bool IsInstalled /// This property checks for both the minified version and the full uncompressed version of jQuery UI. /// These files should exist in the /Resources/Shared/Scripts/jquery directory. /// - [Obsolete("This is managed through the JavaScript Library package. Scheduled removal in v10.0.0.")] + [Obsolete("Deprecated in DotNetNuke 7.3.1. This is managed through the JavaScript Library package. Scheduled removal in v10.0.0.")] public static bool IsUIInstalled { get @@ -165,7 +166,7 @@ public static bool IsHoverIntentRequested /// Gets a value indicating whether gets the HostSetting to determine if we should use the standard jQuery script or the minified jQuery script. /// The HostSetting to determine if we should use the standard jQuery script or the minified jQuery script. /// This is a simple wrapper around the Host.jQueryDebug property. - [Obsolete("This is managed through the JavaScript Library package. Scheduled removal in v10.0.0.")] + [Obsolete("Deprecated in DotNetNuke 7.3.1. This is managed through the JavaScript Library package. Scheduled removal in v10.0.0.")] public static bool UseDebugScript { get @@ -182,7 +183,7 @@ public static bool UseDebugScript /// Gets a value indicating whether gets the HostSetting to determine if we should use a hosted version of the jQuery script. /// The HostSetting to determine if we should use a hosted version of the jQuery script. /// This is a simple wrapper around the Host.jQueryHosted property. - [Obsolete("This is managed through the JavaScript Library package. Scheduled removal in v10.0.0.")] + [Obsolete("Deprecated in DotNetNuke 7.3.1. This is managed through the JavaScript Library package. Scheduled removal in v10.0.0.")] public static bool UseHostedScript { get @@ -258,20 +259,20 @@ public static string UIVersion } } - [Obsolete("This is managed through the JavaScript Library package. Scheduled removal in v10.0.0.")] - public static string JQueryFileMapPath(bool getMinFile) + [DnnDeprecated(7, 3, 1, "This is managed through the JavaScript Library package", RemovalVersion = 10)] + public static partial string JQueryFileMapPath(bool getMinFile) { return HttpContext.Current.Server.MapPath(JQueryFile(getMinFile)); } - [Obsolete("This is managed through the JavaScript Library package. Scheduled removal in v10.0.0.")] - public static string JQueryUIFileMapPath(bool getMinFile) + [DnnDeprecated(7, 3, 1, "This is managed through the JavaScript Library package", RemovalVersion = 10)] + public static partial string JQueryUIFileMapPath(bool getMinFile) { return HttpContext.Current.Server.MapPath(JQueryUIFile(getMinFile)); } - [Obsolete("This is managed through the JavaScript Library package. Scheduled removal in v10.0.0.")] - public static string JQueryFile(bool getMinFile) + [DnnDeprecated(7, 3, 1, "This is managed through the JavaScript Library package", RemovalVersion = 10)] + public static partial string JQueryFile(bool getMinFile) { string jfile = JQueryDebugFile; if (getMinFile) @@ -282,8 +283,8 @@ public static string JQueryFile(bool getMinFile) return jfile; } - [Obsolete("This is managed through the JavaScript Library package. Scheduled removal in v10.0.0.")] - public static string JQueryMigrateFile(bool getMinFile) + [DnnDeprecated(7, 3, 1, "This is managed through the JavaScript Library package", RemovalVersion = 10)] + public static partial string JQueryMigrateFile(bool getMinFile) { string jfile = JQueryMigrateDebugFile; if (getMinFile) @@ -294,8 +295,8 @@ public static string JQueryMigrateFile(bool getMinFile) return jfile; } - [Obsolete("This is managed through the JavaScript Library package. Scheduled removal in v10.0.0.")] - public static string JQueryUIFile(bool getMinFile) + [DnnDeprecated(7, 3, 1, "This is managed through the JavaScript Library package", RemovalVersion = 10)] + public static partial string JQueryUIFile(bool getMinFile) { string jfile = JQueryUIDebugFile; if (getMinFile) @@ -306,8 +307,8 @@ public static string JQueryUIFile(bool getMinFile) return jfile; } - [Obsolete("This is managed through the JavaScript Library package. Scheduled removal in v10.0.0.")] - public static string GetJQueryScriptReference() + [DnnDeprecated(7, 3, 1, "This is managed through the JavaScript Library package", RemovalVersion = 10)] + public static partial string GetJQueryScriptReference() { string scriptsrc = HostedUrl; if (!UseHostedScript) @@ -318,8 +319,8 @@ public static string GetJQueryScriptReference() return scriptsrc; } - [Obsolete("This is managed through the JavaScript Library package. Scheduled removal in v10.0.0.")] - public static string GetJQueryMigrateScriptReference() + [DnnDeprecated(7, 3, 1, "This is managed through the JavaScript Library package", RemovalVersion = 10)] + public static partial string GetJQueryMigrateScriptReference() { string scriptsrc = HostedMigrateUrl; if (!UseHostedScript || string.IsNullOrEmpty(scriptsrc)) @@ -330,8 +331,8 @@ public static string GetJQueryMigrateScriptReference() return scriptsrc; } - [Obsolete("This is managed through the JavaScript Library package. Scheduled removal in v10.0.0.")] - public static string GetJQueryUIScriptReference() + [DnnDeprecated(7, 3, 1, "This is managed through the JavaScript Library package", RemovalVersion = 10)] + public static partial string GetJQueryUIScriptReference() { string scriptsrc = HostedUIUrl; if (!UseHostedScript) @@ -364,60 +365,61 @@ public static void KeepAlive(Page page) ScriptManager.RegisterClientScriptBlock(page, page.GetType(), "PageKeepAlive", scriptBlock, true); } - [Obsolete("Obsoleted in 7.2.0 - registration occurs automatically during page load. Scheduled removal in v10.0.0.")] - public static void RegisterJQuery(Page page) + [DnnDeprecated(7, 2, 0, "Registration occurs automatically during page load", RemovalVersion = 10)] + public static partial void RegisterJQuery(Page page) { JavaScript.RequestRegistration(CommonJs.jQuery); JavaScript.RequestRegistration(CommonJs.jQueryMigrate); } - [Obsolete("Obsoleted in 7.2.0 - registration occurs automatically during page load. Scheduled removal in v10.0.0.")] - public static void RegisterJQueryUI(Page page) + [DnnDeprecated(7, 2, 0, "Registration occurs automatically during page load", RemovalVersion = 10)] + public static partial void RegisterJQueryUI(Page page) { RegisterJQuery(page); JavaScript.RequestRegistration(CommonJs.jQueryUI); } - [Obsolete("Obsoleted in 7.2.0 - registration occurs automatically during page load. Scheduled removal in v10.0.0.")] - public static void RegisterDnnJQueryPlugins(Page page) + [DnnDeprecated(7, 2, 0, "Registration occurs automatically during page load", RemovalVersion = 10)] + public static partial void RegisterDnnJQueryPlugins(Page page) { RegisterJQueryUI(page); RegisterHoverIntent(page); JavaScript.RequestRegistration(CommonJs.DnnPlugins); } - [Obsolete("Obsoleted in 7.2.0 - registration occurs automatically during page load. Scheduled removal in v10.0.0.")] - public static void RegisterHoverIntent(Page page) + [DnnDeprecated(7, 2, 0, "Use JavaScript.RequestRegistration(CommonJs.HoverIntent)", RemovalVersion = 10)] + public static partial void RegisterHoverIntent(Page page) { JavaScript.RequestRegistration(CommonJs.HoverIntent); } - public static void RegisterFileUpload(Page page) + [DnnDeprecated(7, 2, 0, "Use JavaScript.RequestRegistration(CommonJs.jQueryFileUpload)", RemovalVersion = 10)] + public static partial void RegisterFileUpload(Page page) { JavaScript.RequestRegistration(CommonJs.jQueryFileUpload); } - [Obsolete("Obsoleted in 7.2.0 - use JavaScript.RequestRegistration(CommonJs.jQuery);. Scheduled removal in v10.0.0.")] - public static void RequestRegistration() + [DnnDeprecated(7, 2, 0, "Use JavaScript.RequestRegistration(CommonJs.jQuery)", RemovalVersion = 10)] + public static partial void RequestRegistration() { JavaScript.RequestRegistration(CommonJs.jQuery); JavaScript.RequestRegistration(CommonJs.jQueryMigrate); } - [Obsolete("Obsoleted in 7.2.0 - use JavaScript.RequestRegistration(CommonJs.jQueryUI);. Scheduled removal in v10.0.0.")] - public static void RequestUIRegistration() + [DnnDeprecated(7, 2, 0, "Use JavaScript.RequestRegistration(CommonJs.jQueryUI)", RemovalVersion = 10)] + public static partial void RequestUIRegistration() { JavaScript.RequestRegistration(CommonJs.jQueryUI); } - [Obsolete("Obsoleted in 7.2.0 - use JavaScript.RequestRegistration(CommonJs.DnnPlugins);. Scheduled removal in v10.0.0.")] - public static void RequestDnnPluginsRegistration() + [DnnDeprecated(7, 2, 0, "Use JavaScript.RequestRegistration(CommonJs.DnnPlugins)", RemovalVersion = 10)] + public static partial void RequestDnnPluginsRegistration() { JavaScript.RequestRegistration(CommonJs.DnnPlugins); } - [Obsolete("Obsoleted in 7.2.0 - use JavaScript.RequestRegistration(CommonJs.HoverIntent);. Scheduled removal in v10.0.0.")] - public static void RequestHoverIntentRegistration() + [DnnDeprecated(7, 2, 0, "Use JavaScript.RequestRegistration(CommonJs.HoverIntent)", RemovalVersion = 10)] + public static partial void RequestHoverIntentRegistration() { JavaScript.RequestRegistration(CommonJs.HoverIntent); } diff --git a/DNN Platform/Library/Obsolete/CBO.cs b/DNN Platform/Library/Obsolete/CBO.cs index 865bb295df8..55eb8bf1032 100644 --- a/DNN Platform/Library/Obsolete/CBO.cs +++ b/DNN Platform/Library/Obsolete/CBO.cs @@ -7,52 +7,53 @@ namespace DotNetNuke.Common.Utilities using System.Collections.Generic; using System.ComponentModel; using System.Data; - + using DotNetNuke.Entities.Modules; - + using DotNetNuke.Internal.SourceGenerators; + /// The CBO class generates objects. public partial class CBO { [EditorBrowsable(EditorBrowsableState.Never)] - [Obsolete("Obsolete in DotNetNuke 7.3. Use CreateObject(bool). Scheduled removal in v10.0.0.")] - public static TObject CreateObject() + [DnnDeprecated(7, 3, 0, "Use CreateObject(bool)", RemovalVersion = 10)] + public static partial TObject CreateObject() { return (TObject)CreateObjectInternal(typeof(TObject), false); } [EditorBrowsable(EditorBrowsableState.Never)] - [Obsolete("Obsolete in DotNetNuke 7.3. Use CreateObject(bool). Scheduled removal in v10.0.0.")] - public static object CreateObject(Type objType, bool initialise) + [DnnDeprecated(7, 3, 0, "Use CreateObject(bool)", RemovalVersion = 10)] + public static partial object CreateObject(Type objType, bool initialise) { return CreateObjectInternal(objType, initialise); } [EditorBrowsable(EditorBrowsableState.Never)] - [Obsolete("Obsolete in DotNetNuke 7.3. Use FillDictionary(string keyField, IDataReader dr). Scheduled removal in v10.0.0.")] - public static IDictionary FillDictionary(IDataReader dr) + [DnnDeprecated(7, 3, 0, "Use FillDictionary(string keyField, IDataReader dr)", RemovalVersion = 10)] + public static partial IDictionary FillDictionary(IDataReader dr) where TItem : IHydratable { return FillDictionaryFromReader("KeyID", dr, new Dictionary(), true); } [EditorBrowsable(EditorBrowsableState.Never)] - [Obsolete("Obsolete in DotNetNuke 7.3. Use FillDictionary(string keyField, IDataReader dr, IDictionary objDictionary). Scheduled removal in v10.0.0.")] - public static IDictionary FillDictionary(IDataReader dr, ref IDictionary objToFill) + [DnnDeprecated(7, 3, 0, "Use FillDictionary(string keyField, IDataReader dr, IDictionary objDictionary)", RemovalVersion = 10)] + public static partial IDictionary FillDictionary(IDataReader dr, ref IDictionary objToFill) where TItem : IHydratable { return FillDictionaryFromReader("KeyID", dr, objToFill, true); } [EditorBrowsable(EditorBrowsableState.Never)] - [Obsolete("Obsolete in DotNetNuke 7.3. Replaced by FillObject . Scheduled removal in v10.0.0.")] - public static object FillObject(IDataReader dr, Type objType) + [DnnDeprecated(7, 3, 0, "Replaced by FillObject ", RemovalVersion = 10)] + public static partial object FillObject(IDataReader dr, Type objType) { return CreateObjectFromReader(objType, dr, true); } [EditorBrowsable(EditorBrowsableState.Never)] - [Obsolete("Obsolete in DotNetNuke 7.3. Replaced by FillObject . Scheduled removal in v10.0.0.")] - public static object FillObject(IDataReader dr, Type objType, bool closeReader) + [DnnDeprecated(7, 3, 0, "Replaced by FillObject ", RemovalVersion = 10)] + public static partial object FillObject(IDataReader dr, Type objType, bool closeReader) { return CreateObjectFromReader(objType, dr, closeReader); } diff --git a/DNN Platform/Library/Obsolete/EventLogController.cs b/DNN Platform/Library/Obsolete/EventLogController.cs index b172b5b0099..2b6f11f4248 100644 --- a/DNN Platform/Library/Obsolete/EventLogController.cs +++ b/DNN Platform/Library/Obsolete/EventLogController.cs @@ -1,350 +1,350 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information -namespace DotNetNuke.Services.Log.EventLog -{ - using System; - using System.Collections; - using System.Collections.Generic; - using System.Linq; - - using DotNetNuke.Abstractions.Logging; - using DotNetNuke.Abstractions.Portals; - using DotNetNuke.Common; - using DotNetNuke.Entities.Portals; - using DotNetNuke.Framework; - - using Microsoft.Extensions.DependencyInjection; - - [Obsolete("Deprecated in v9.8.1, use dependency injection to resolve IEventLogger, IEventLogService or IEventLogConfigService instead, scheduled removal in v11.")] -#pragma warning disable SA1601 // Partial elements should be documented, not documenting, the whole class is deprecated. -#pragma warning disable SA1600 // Elements should be documented, not documenting, the whole class is deprecated. - public partial class EventLogController : ServiceLocator, IEventLogController - { - [Obsolete("Deprecated in 9.8.0. Use 'DotNetNuke.Abstractions.Logging.EventLogType' instead. Scheduled for removal in v11.0.0.")] - [System.Diagnostics.CodeAnalysis.SuppressMessage( - "StyleCop.CSharp.DocumentationRules", - "SA1602:Enumeration items should be documented", - Justification = "Not documenting since the whole class is deprecated.")] - public enum EventLogType - { - USER_CREATED = 0, - USER_DELETED = 1, - LOGIN_SUPERUSER = 2, - LOGIN_SUCCESS = 3, - LOGIN_FAILURE = 4, - LOGIN_USERLOCKEDOUT = 5, - LOGIN_USERNOTAPPROVED = 6, - CACHE_REFRESHED = 7, - PASSWORD_SENT_SUCCESS = 8, - PASSWORD_SENT_FAILURE = 9, - LOG_NOTIFICATION_FAILURE = 10, - PORTAL_CREATED = 11, - PORTAL_DELETED = 12, - PORTALGROUP_CREATED = 13, - PORTALGROUP_DELETED = 14, - PORTAL_ADDEDTOPORTALGROUP = 15, - PORTAL_REMOVEDFROMPORTALGROUP = 16, - TAB_CREATED = 17, - TAB_UPDATED = 18, - TAB_DELETED = 19, - TAB_SENT_TO_RECYCLE_BIN = 20, - TAB_RESTORED = 21, - USER_ROLE_CREATED = 22, - USER_ROLE_DELETED = 23, - USER_ROLE_UPDATED = 24, - ROLE_CREATED = 25, - ROLE_UPDATED = 26, - ROLE_DELETED = 27, - MODULE_CREATED = 28, - MODULE_UPDATED = 29, - MODULE_DELETED = 30, - MODULE_SENT_TO_RECYCLE_BIN = 31, - MODULE_RESTORED = 32, - SCHEDULER_EVENT_STARTED = 33, - SCHEDULER_EVENT_PROGRESSING = 34, - SCHEDULER_EVENT_COMPLETED = 35, - APPLICATION_START = 36, - APPLICATION_END = 37, - APPLICATION_SHUTTING_DOWN = 38, - SCHEDULER_STARTED = 39, - SCHEDULER_SHUTTING_DOWN = 40, - SCHEDULER_STOPPED = 41, - ADMIN_ALERT = 42, - HOST_ALERT = 43, - CACHE_REMOVED = 44, - CACHE_EXPIRED = 45, - CACHE_UNDERUSED = 46, - CACHE_DEPENDENCYCHANGED = 47, - CACHE_OVERFLOW = 48, - CACHE_REFRESH = 49, - LISTENTRY_CREATED = 50, - LISTENTRY_UPDATED = 51, - LISTENTRY_DELETED = 52, - DESKTOPMODULE_CREATED = 53, - DESKTOPMODULE_UPDATED = 54, - DESKTOPMODULE_DELETED = 55, - SKINCONTROL_CREATED = 56, - SKINCONTROL_UPDATED = 57, - SKINCONTROL_DELETED = 58, - PORTALALIAS_CREATED = 59, - PORTALALIAS_UPDATED = 60, - PORTALALIAS_DELETED = 61, - PROFILEPROPERTY_CREATED = 62, - PROFILEPROPERTY_UPDATED = 63, - PROFILEPROPERTY_DELETED = 64, - USER_UPDATED = 65, - DESKTOPMODULEPERMISSION_CREATED = 66, - DESKTOPMODULEPERMISSION_UPDATED = 67, - DESKTOPMODULEPERMISSION_DELETED = 68, - PERMISSION_CREATED = 69, - PERMISSION_UPDATED = 70, - PERMISSION_DELETED = 71, - TABPERMISSION_CREATED = 72, - TABPERMISSION_UPDATED = 73, - TABPERMISSION_DELETED = 74, - AUTHENTICATION_CREATED = 75, - AUTHENTICATION_UPDATED = 76, - AUTHENTICATION_DELETED = 77, - FILE_ADDED = 78, - FILE_CHANGED = 79, - FILE_DELETED = 80, - FILE_DOWNLOADED = 81, - FILE_MOVED = 82, - FILE_OVERWRITTEN = 83, - FILE_RENAMED = 84, - FILE_METADATACHANGED = 85, - FOLDER_CREATED = 86, - FOLDER_UPDATED = 87, - FOLDER_DELETED = 88, - PACKAGE_CREATED = 89, - PACKAGE_UPDATED = 90, - PACKAGE_DELETED = 91, - LANGUAGEPACK_CREATED = 92, - LANGUAGEPACK_UPDATED = 93, - LANGUAGEPACK_DELETED = 94, - LANGUAGE_CREATED = 95, - LANGUAGE_UPDATED = 96, - LANGUAGE_DELETED = 97, - LIBRARY_UPDATED = 98, - SKINPACKAGE_CREATED = 99, - SKINPACKAGE_UPDATED = 100, - SKINPACKAGE_DELETED = 101, - SCHEDULE_CREATED = 102, - SCHEDULE_UPDATED = 103, - SCHEDULE_DELETED = 104, - HOST_SETTING_CREATED = 105, - HOST_SETTING_UPDATED = 106, - HOST_SETTING_DELETED = 107, - PORTALDESKTOPMODULE_CREATED = 108, - PORTALDESKTOPMODULE_UPDATED = 109, - PORTALDESKTOPMODULE_DELETED = 110, - TABMODULE_CREATED = 111, - TABMODULE_UPDATED = 112, - TABMODULE_DELETED = 113, - TABMODULE_SETTING_CREATED = 114, - TABMODULE_SETTING_UPDATED = 115, - TABMODULE_SETTING_DELETED = 116, - MODULE_SETTING_CREATED = 117, - MODULE_SETTING_UPDATED = 118, - MODULE_SETTING_DELETED = 119, - PORTAL_SETTING_CREATED = 120, - PORTAL_SETTING_UPDATED = 121, - PORTAL_SETTING_DELETED = 122, - PORTALINFO_CREATED = 123, - PORTALINFO_UPDATED = 124, - PORTALINFO_DELETED = 125, - AUTHENTICATION_USER_CREATED = 126, - AUTHENTICATION_USER_UPDATED = 127, - AUTHENTICATION_USER_DELETED = 128, - LANGUAGETOPORTAL_CREATED = 129, - LANGUAGETOPORTAL_UPDATED = 130, - LANGUAGETOPORTAL_DELETED = 131, - TAB_ORDER_UPDATED = 132, - TAB_SETTING_CREATED = 133, - TAB_SETTING_UPDATED = 134, - TAB_SETTING_DELETED = 135, - HOST_SQL_EXECUTED = 136, - USER_RESTORED = 137, - USER_REMOVED = 138, - USER_IMPERSONATED = 139, - USERNAME_UPDATED = 140, - IP_LOGIN_BANNED = 141, - PAGE_NOT_FOUND_404 = 142, - TABURL_CREATED = 143, - TABURL_UPDATED = 144, - TABURL_DELETED = 145, - SCRIPT_COLLISION = 146, - POTENTIAL_PAYPAL_PAYMENT_FRAUD = 147, - WEBSERVER_CREATED = 148, - WEBSERVER_UPDATED = 149, - WEBSERVER_DISABLED = 150, - WEBSERVER_ENABLED = 151, - WEBSERVER_PINGFAILED = 152, +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information +namespace DotNetNuke.Services.Log.EventLog +{ + using System; + using System.Collections; + using System.Collections.Generic; + using System.Linq; + + using DotNetNuke.Abstractions.Logging; + using DotNetNuke.Abstractions.Portals; + using DotNetNuke.Common; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Framework; + using DotNetNuke.Internal.SourceGenerators; + using Microsoft.Extensions.DependencyInjection; + + [DnnDeprecated(9, 8, 1, "Use dependency injection to resolve IEventLogger, IEventLogService or IEventLogConfigService instead")] +#pragma warning disable SA1601 // Partial elements should be documented, not documenting, the whole class is deprecated. +#pragma warning disable SA1600 // Elements should be documented, not documenting, the whole class is deprecated. + public partial class EventLogController : ServiceLocator, IEventLogController + { + [Obsolete("Deprecated in DotNetNuke 9.8.0. Use 'DotNetNuke.Abstractions.Logging.EventLogType' instead. Scheduled removal in v11.0.0.")] + [System.Diagnostics.CodeAnalysis.SuppressMessage( + "StyleCop.CSharp.DocumentationRules", + "SA1602:Enumeration items should be documented", + Justification = "Not documenting since the whole class is deprecated.")] + public enum EventLogType + { + USER_CREATED = 0, + USER_DELETED = 1, + LOGIN_SUPERUSER = 2, + LOGIN_SUCCESS = 3, + LOGIN_FAILURE = 4, + LOGIN_USERLOCKEDOUT = 5, + LOGIN_USERNOTAPPROVED = 6, + CACHE_REFRESHED = 7, + PASSWORD_SENT_SUCCESS = 8, + PASSWORD_SENT_FAILURE = 9, + LOG_NOTIFICATION_FAILURE = 10, + PORTAL_CREATED = 11, + PORTAL_DELETED = 12, + PORTALGROUP_CREATED = 13, + PORTALGROUP_DELETED = 14, + PORTAL_ADDEDTOPORTALGROUP = 15, + PORTAL_REMOVEDFROMPORTALGROUP = 16, + TAB_CREATED = 17, + TAB_UPDATED = 18, + TAB_DELETED = 19, + TAB_SENT_TO_RECYCLE_BIN = 20, + TAB_RESTORED = 21, + USER_ROLE_CREATED = 22, + USER_ROLE_DELETED = 23, + USER_ROLE_UPDATED = 24, + ROLE_CREATED = 25, + ROLE_UPDATED = 26, + ROLE_DELETED = 27, + MODULE_CREATED = 28, + MODULE_UPDATED = 29, + MODULE_DELETED = 30, + MODULE_SENT_TO_RECYCLE_BIN = 31, + MODULE_RESTORED = 32, + SCHEDULER_EVENT_STARTED = 33, + SCHEDULER_EVENT_PROGRESSING = 34, + SCHEDULER_EVENT_COMPLETED = 35, + APPLICATION_START = 36, + APPLICATION_END = 37, + APPLICATION_SHUTTING_DOWN = 38, + SCHEDULER_STARTED = 39, + SCHEDULER_SHUTTING_DOWN = 40, + SCHEDULER_STOPPED = 41, + ADMIN_ALERT = 42, + HOST_ALERT = 43, + CACHE_REMOVED = 44, + CACHE_EXPIRED = 45, + CACHE_UNDERUSED = 46, + CACHE_DEPENDENCYCHANGED = 47, + CACHE_OVERFLOW = 48, + CACHE_REFRESH = 49, + LISTENTRY_CREATED = 50, + LISTENTRY_UPDATED = 51, + LISTENTRY_DELETED = 52, + DESKTOPMODULE_CREATED = 53, + DESKTOPMODULE_UPDATED = 54, + DESKTOPMODULE_DELETED = 55, + SKINCONTROL_CREATED = 56, + SKINCONTROL_UPDATED = 57, + SKINCONTROL_DELETED = 58, + PORTALALIAS_CREATED = 59, + PORTALALIAS_UPDATED = 60, + PORTALALIAS_DELETED = 61, + PROFILEPROPERTY_CREATED = 62, + PROFILEPROPERTY_UPDATED = 63, + PROFILEPROPERTY_DELETED = 64, + USER_UPDATED = 65, + DESKTOPMODULEPERMISSION_CREATED = 66, + DESKTOPMODULEPERMISSION_UPDATED = 67, + DESKTOPMODULEPERMISSION_DELETED = 68, + PERMISSION_CREATED = 69, + PERMISSION_UPDATED = 70, + PERMISSION_DELETED = 71, + TABPERMISSION_CREATED = 72, + TABPERMISSION_UPDATED = 73, + TABPERMISSION_DELETED = 74, + AUTHENTICATION_CREATED = 75, + AUTHENTICATION_UPDATED = 76, + AUTHENTICATION_DELETED = 77, + FILE_ADDED = 78, + FILE_CHANGED = 79, + FILE_DELETED = 80, + FILE_DOWNLOADED = 81, + FILE_MOVED = 82, + FILE_OVERWRITTEN = 83, + FILE_RENAMED = 84, + FILE_METADATACHANGED = 85, + FOLDER_CREATED = 86, + FOLDER_UPDATED = 87, + FOLDER_DELETED = 88, + PACKAGE_CREATED = 89, + PACKAGE_UPDATED = 90, + PACKAGE_DELETED = 91, + LANGUAGEPACK_CREATED = 92, + LANGUAGEPACK_UPDATED = 93, + LANGUAGEPACK_DELETED = 94, + LANGUAGE_CREATED = 95, + LANGUAGE_UPDATED = 96, + LANGUAGE_DELETED = 97, + LIBRARY_UPDATED = 98, + SKINPACKAGE_CREATED = 99, + SKINPACKAGE_UPDATED = 100, + SKINPACKAGE_DELETED = 101, + SCHEDULE_CREATED = 102, + SCHEDULE_UPDATED = 103, + SCHEDULE_DELETED = 104, + HOST_SETTING_CREATED = 105, + HOST_SETTING_UPDATED = 106, + HOST_SETTING_DELETED = 107, + PORTALDESKTOPMODULE_CREATED = 108, + PORTALDESKTOPMODULE_UPDATED = 109, + PORTALDESKTOPMODULE_DELETED = 110, + TABMODULE_CREATED = 111, + TABMODULE_UPDATED = 112, + TABMODULE_DELETED = 113, + TABMODULE_SETTING_CREATED = 114, + TABMODULE_SETTING_UPDATED = 115, + TABMODULE_SETTING_DELETED = 116, + MODULE_SETTING_CREATED = 117, + MODULE_SETTING_UPDATED = 118, + MODULE_SETTING_DELETED = 119, + PORTAL_SETTING_CREATED = 120, + PORTAL_SETTING_UPDATED = 121, + PORTAL_SETTING_DELETED = 122, + PORTALINFO_CREATED = 123, + PORTALINFO_UPDATED = 124, + PORTALINFO_DELETED = 125, + AUTHENTICATION_USER_CREATED = 126, + AUTHENTICATION_USER_UPDATED = 127, + AUTHENTICATION_USER_DELETED = 128, + LANGUAGETOPORTAL_CREATED = 129, + LANGUAGETOPORTAL_UPDATED = 130, + LANGUAGETOPORTAL_DELETED = 131, + TAB_ORDER_UPDATED = 132, + TAB_SETTING_CREATED = 133, + TAB_SETTING_UPDATED = 134, + TAB_SETTING_DELETED = 135, + HOST_SQL_EXECUTED = 136, + USER_RESTORED = 137, + USER_REMOVED = 138, + USER_IMPERSONATED = 139, + USERNAME_UPDATED = 140, + IP_LOGIN_BANNED = 141, + PAGE_NOT_FOUND_404 = 142, + TABURL_CREATED = 143, + TABURL_UPDATED = 144, + TABURL_DELETED = 145, + SCRIPT_COLLISION = 146, + POTENTIAL_PAYPAL_PAYMENT_FRAUD = 147, + WEBSERVER_CREATED = 148, + WEBSERVER_UPDATED = 149, + WEBSERVER_DISABLED = 150, + WEBSERVER_ENABLED = 151, + WEBSERVER_PINGFAILED = 152, FOLDER_MOVED = 153, PORTALPERMISSION_DELETED = 154, PORTALPERMISSION_CREATED = 155, - PORTALPERMISSION_UPDATED = 156, - } - - [Obsolete("Deprecated in 9.8.0. Use Dependency Injection to resolve 'DotNetNuke.Abstractions.Logging.IEventLogger' instead. Scheduled for removal in v11.0.0.")] - public static void AddSettingLog(EventLogType logTypeKey, string idFieldName, int idValue, string settingName, string settingValue, int userId) => - Globals.DependencyProvider.GetRequiredService() - .AddSettingLog((Abstractions.Logging.EventLogType)logTypeKey, idFieldName, idValue, settingName, settingValue, userId); - - /// - [Obsolete("Deprecated in 9.8.0. Use Dependency Injection to resolve 'DotNetNuke.Abstractions.Logging.IEventLogger' instead. Scheduled for removal in v11.0.0.")] - public void AddLog(string propertyName, string propertyValue, EventLogType logType) => - this.EventLogger.AddLog(propertyName, propertyValue, (Abstractions.Logging.EventLogType)logType); - - /// - [Obsolete("Deprecated in DNN 9.7. It has been replaced by the overload taking IPortalSettings. Scheduled removal in v11.0.0.")] - public void AddLog(string propertyName, string propertyValue, PortalSettings portalSettings, int userID, EventLogType logType) => - this.AddLog(propertyName, propertyValue, (IPortalSettings)portalSettings, userID, logType); - - /// - [Obsolete("Deprecated in 9.8.0. Use Dependency Injection to resolve 'DotNetNuke.Abstractions.Logging.IEventLogger' instead. Scheduled for removal in v11.0.0.")] - public void AddLog(string propertyName, string propertyValue, IPortalSettings portalSettings, int userID, EventLogType logType) => - this.EventLogger.AddLog(propertyName, propertyValue, portalSettings, userID, (Abstractions.Logging.EventLogType)logType); - - /// - [Obsolete("Deprecated in DNN 9.7. It has been replaced by the overload taking IPortalSettings. Scheduled removal in v11.0.0.")] - public void AddLog(string propertyName, string propertyValue, PortalSettings portalSettings, int userID, string logType) => - this.AddLog(propertyName, propertyValue, (IPortalSettings)portalSettings, userID, logType); - - /// - [Obsolete("Deprecated in 9.8.0. Use Dependency Injection to resolve 'DotNetNuke.Abstractions.Logging.IEventLogger' instead. Scheduled for removal in v11.0.0.")] - public void AddLog(string propertyName, string propertyValue, IPortalSettings portalSettings, int userID, string logType) => - this.EventLogger.AddLog(propertyName, propertyValue, portalSettings, userID, logType); - - /// - [Obsolete("Deprecated in DNN 9.7. It has been replaced by the overload taking IPortalSettings. Scheduled removal in v11.0.0.")] - public void AddLog(LogProperties properties, PortalSettings portalSettings, int userID, string logTypeKey, bool bypassBuffering) => - this.AddLog(properties, (IPortalSettings)portalSettings, userID, logTypeKey, bypassBuffering); - - /// - [Obsolete("Deprecated in 9.8.0. Use Dependency Injection to resolve 'DotNetNuke.Abstractions.Logging.IEventLogger' instead. Scheduled for removal in v11.0.0.")] - public void AddLog(LogProperties properties, IPortalSettings portalSettings, int userID, string logTypeKey, bool bypassBuffering) => - this.EventLogger.AddLog(properties, portalSettings, userID, logTypeKey, bypassBuffering); - - /// - [Obsolete("Deprecated in DNN 9.7. It has been replaced by the overload taking IPortalSettings. Scheduled removal in v11.0.0.")] - public void AddLog(PortalSettings portalSettings, int userID, EventLogType logType) => - this.AddLog((IPortalSettings)portalSettings, userID, logType); - - [Obsolete("Deprecated in 9.8.0. Use Dependency Injection to resolve 'DotNetNuke.Abstractions.Logging.IEventLogger' instead. Scheduled for removal in v11.0.0.")] - public void AddLog(IPortalSettings portalSettings, int userID, EventLogType logType) => - this.EventLogger.AddLog(portalSettings, userID, (Abstractions.Logging.EventLogType)logType); - - /// - [Obsolete("Deprecated in DNN 9.7. It has been replaced by the overload taking IPortalSettings. Scheduled removal in v11.0.0.")] - public void AddLog(object businessObject, PortalSettings portalSettings, int userID, string userName, EventLogType logType) => - this.AddLog(businessObject, (IPortalSettings)portalSettings, userID, userName, logType); - - /// - [Obsolete("Deprecated in 9.8.0. Use Dependency Injection to resolve 'DotNetNuke.Abstractions.Logging.IEventLogger' instead. Scheduled for removal in v11.0.0.")] - public void AddLog(object businessObject, IPortalSettings portalSettings, int userID, string userName, EventLogType logType) => - this.EventLogger.AddLog(businessObject, portalSettings, userID, userName, (Abstractions.Logging.EventLogType)logType); - - /// - [Obsolete("Deprecated in DNN 9.7. It has been replaced by the overload taking IPortalSettings. Scheduled removal in v11.0.0.")] - public void AddLog(object businessObject, PortalSettings portalSettings, int userID, string userName, string logType) => - this.AddLog(businessObject, (IPortalSettings)portalSettings, userID, userName, logType); - - /// - [Obsolete("Deprecated in 9.8.0. Use Dependency Injection to resolve 'DotNetNuke.Abstractions.Logging.IEventLogger' instead. Scheduled for removal in v11.0.0.")] - public void AddLog(object businessObject, IPortalSettings portalSettings, int userID, string userName, string logType) => - this.EventLogger.AddLog(businessObject, portalSettings, userID, userName, logType); - - /// - [Obsolete("Deprecated in 9.8.0. Use Dependency Injection to resolve 'DotNetNuke.Abstractions.Logging.IEventLogger' instead. Scheduled for removal in v11.0.0.")] - public void AddLog(LogInfo logInfo) => - this.EventLogger.AddLog(logInfo); - - /// - [Obsolete("Deprecated in 9.8.0. Use Dependency Injection to resolve 'DotNetNuke.Abstractions.Logging.IEventLogConfigService' instead. Scheduled for removal in v11.0.0.")] - public void AddLogType(string configFile, string fallbackConfigFile) => - this.EventLogConfigService.AddLogType(configFile, fallbackConfigFile); - - /// - [Obsolete("Deprecated in 9.8.0. Use Dependency Injection to resolve 'DotNetNuke.Abstractions.Logging.IEventLogConfigService' instead. Scheduled for removal in v11.0.0.")] - public void AddLogType(LogTypeInfo logType) => - this.EventLogConfigService.AddLogType(logType); - - /// - [Obsolete("Deprecated in 9.8.0. Use Dependency Injection to resolve 'DotNetNuke.Abstractions.Logging.IEventLogConfigService' instead. Scheduled for removal in v11.0.0.")] - public void AddLogTypeConfigInfo(LogTypeConfigInfo logTypeConfig) => - this.EventLogConfigService.AddLogTypeConfigInfo(logTypeConfig); - - /// - [Obsolete("Deprecated in 9.8.0. Use Dependency Injection to resolve 'DotNetNuke.Abstractions.Logging.IEventLogService' instead. Scheduled for removal in v11.0.0.")] - public void ClearLog() => - this.EventLogService.ClearLog(); - - /// - [Obsolete("Deprecated in 9.8.0. Use Dependency Injection to resolve 'DotNetNuke.Abstractions.Logging.IEventLogService' instead. Scheduled for removal in v11.0.0.")] - public void DeleteLog(LogInfo logInfo) => - this.EventLogService.DeleteLog(logInfo); - - /// - [Obsolete("Deprecated in 9.8.0. Use Dependency Injection to resolve 'DotNetNuke.Abstractions.Logging.IEventLogConfigService' instead. Scheduled for removal in v11.0.0.")] - public void DeleteLogType(LogTypeInfo logType) => - this.EventLogConfigService.DeleteLogType(logType); - - /// - [Obsolete("Deprecated in 9.8.0. Use Dependency Injection to resolve 'DotNetNuke.Abstractions.Logging.IEventLogConfigService' instead. Scheduled for removal in v11.0.0.")] - public void DeleteLogTypeConfigInfo(LogTypeConfigInfo logTypeConfig) => - this.EventLogConfigService.DeleteLogTypeConfigInfo(logTypeConfig); - - /// - [Obsolete("Deprecated in 9.8.0. Use Dependency Injection to resolve 'DotNetNuke.Abstractions.Logging.IEventLogService' instead. Scheduled for removal in v11.0.0.")] - public List GetLogs(int portalID, string logType, int pageSize, int pageIndex, ref int totalRecords) => - this.EventLogService.GetLogs(portalID, logType, pageSize, pageIndex, ref totalRecords).Cast().ToList(); - - /// - [Obsolete("Deprecated in 9.8.0. Use Dependency Injection to resolve 'DotNetNuke.Abstractions.Logging.IEventLogConfigService' instead. Scheduled for removal in v11.0.0.")] - public ArrayList GetLogTypeConfigInfo() => - LogController.Instance.GetLogTypeConfigInfo(); - - /// - [Obsolete("Deprecated in 9.8.0. Use Dependency Injection to resolve 'DotNetNuke.Abstractions.Logging.IEventLogConfigService' instead. Scheduled for removal in v11.0.0.")] - public LogTypeConfigInfo GetLogTypeConfigInfoByID(string id) => - (LogTypeConfigInfo)this.EventLogConfigService.GetLogTypeConfigInfoByID(id); - - /// - [Obsolete("Deprecated in 9.8.0. Use Dependency Injection to resolve 'DotNetNuke.Abstractions.Logging.IEventLogConfigService' instead. Scheduled for removal in v11.0.0.")] - public Dictionary GetLogTypeInfoDictionary() => - this.EventLogConfigService - .GetLogTypeInfoDictionary() - .ToDictionary(key => key.Key, value => (LogTypeInfo)value.Value); - - /// - [Obsolete("Deprecated in 9.8.0. Use Dependency Injection to resolve 'DotNetNuke.Abstractions.Logging.IEventLogService.GetLog()' instead. Scheduled for removal in v11.0.0.")] - public object GetSingleLog(LogInfo log, LoggingProvider.ReturnType returnType) => - LogController.Instance.GetSingleLog(log, returnType); - - /// - [Obsolete("Deprecated in 9.8.0. Use Dependency Injection to resolve 'DotNetNuke.Abstractions.Logging.IEventLogService' instead. Scheduled for removal in v11.0.0.")] - public void PurgeLogBuffer() => - this.EventLogService.PurgeLogBuffer(); - - /// - [Obsolete("Deprecated in 9.8.0. Use Dependency Injection to resolve 'DotNetNuke.Abstractions.Logging.IEventLogConfigService' instead. Scheduled for removal in v11.0.0.")] - public virtual void UpdateLogTypeConfigInfo(LogTypeConfigInfo logTypeConfig) => - this.EventLogConfigService.UpdateLogTypeConfigInfo(logTypeConfig); - - /// - [Obsolete("Deprecated in 9.8.0. Use Dependency Injection to resolve 'DotNetNuke.Abstractions.Logging.IEventLogConfigService' instead. Scheduled for removal in v11.0.0.")] - public virtual void UpdateLogType(LogTypeInfo logType) => - this.EventLogConfigService.UpdateLogType(logType); - - /// - [Obsolete("Deprecated in 9.8.0. Use Dependency Injection to resolve 'DotNetNuke.Abstractions.Logging.IEventLogger' instead. Scheduled for removal in v11.0.0.")] -#pragma warning disable CS0809 // Obsolete member overrides non-obsolete member - protected override Func GetFactory() => -#pragma warning restore CS0809 // Obsolete member overrides non-obsolete member - () => new EventLogController(); - } -#pragma warning restore SA1601 // Partial elements should be documented -#pragma warning restore SA1600 // Elements should be documented -} + PORTALPERMISSION_UPDATED = 156, + } + + [DnnDeprecated(9, 8, 0, "Use Dependency Injection to resolve 'DotNetNuke.Abstractions.Logging.IEventLogger' instead")] + public static partial void AddSettingLog(EventLogType logTypeKey, string idFieldName, int idValue, string settingName, string settingValue, int userId) => + Globals.DependencyProvider.GetRequiredService() + .AddSettingLog((Abstractions.Logging.EventLogType)logTypeKey, idFieldName, idValue, settingName, settingValue, userId); + + /// + [DnnDeprecated(9, 8, 0, "Use Dependency Injection to resolve 'DotNetNuke.Abstractions.Logging.IEventLogger' instead")] + public partial void AddLog(string propertyName, string propertyValue, EventLogType logType) => + this.EventLogger.AddLog(propertyName, propertyValue, (Abstractions.Logging.EventLogType)logType); + + /// + [DnnDeprecated(9, 7, 0, "It has been replaced by the overload taking IPortalSettings")] + public partial void AddLog(string propertyName, string propertyValue, PortalSettings portalSettings, int userID, EventLogType logType) => + this.AddLog(propertyName, propertyValue, (IPortalSettings)portalSettings, userID, logType); + + /// + [DnnDeprecated(9, 8, 0, "Use Dependency Injection to resolve 'DotNetNuke.Abstractions.Logging.IEventLogger' instead")] + public partial void AddLog(string propertyName, string propertyValue, IPortalSettings portalSettings, int userID, EventLogType logType) => + this.EventLogger.AddLog(propertyName, propertyValue, portalSettings, userID, (Abstractions.Logging.EventLogType)logType); + + /// + [DnnDeprecated(9, 7, 0, "It has been replaced by the overload taking IPortalSettings")] + public partial void AddLog(string propertyName, string propertyValue, PortalSettings portalSettings, int userID, string logType) => + this.AddLog(propertyName, propertyValue, (IPortalSettings)portalSettings, userID, logType); + + /// + [DnnDeprecated(9, 8, 0, "Use Dependency Injection to resolve 'DotNetNuke.Abstractions.Logging.IEventLogger' instead")] + public partial void AddLog(string propertyName, string propertyValue, IPortalSettings portalSettings, int userID, string logType) => + this.EventLogger.AddLog(propertyName, propertyValue, portalSettings, userID, logType); + + /// + [DnnDeprecated(9, 7, 0, "It has been replaced by the overload taking IPortalSettings")] + public partial void AddLog(LogProperties properties, PortalSettings portalSettings, int userID, string logTypeKey, bool bypassBuffering) => + this.AddLog(properties, (IPortalSettings)portalSettings, userID, logTypeKey, bypassBuffering); + + /// + [DnnDeprecated(9, 8, 0, "Use Dependency Injection to resolve 'DotNetNuke.Abstractions.Logging.IEventLogger' instead")] + public partial void AddLog(LogProperties properties, IPortalSettings portalSettings, int userID, string logTypeKey, bool bypassBuffering) => + this.EventLogger.AddLog(properties, portalSettings, userID, logTypeKey, bypassBuffering); + + /// + [DnnDeprecated(9, 7, 0, "It has been replaced by the overload taking IPortalSettings")] + public partial void AddLog(PortalSettings portalSettings, int userID, EventLogType logType) => + this.AddLog((IPortalSettings)portalSettings, userID, logType); + + [DnnDeprecated(9, 8, 0, "Use Dependency Injection to resolve 'DotNetNuke.Abstractions.Logging.IEventLogger' instead")] + public partial void AddLog(IPortalSettings portalSettings, int userID, EventLogType logType) => + this.EventLogger.AddLog(portalSettings, userID, (Abstractions.Logging.EventLogType)logType); + + /// + [DnnDeprecated(9, 7, 0, "It has been replaced by the overload taking IPortalSettings")] + public partial void AddLog(object businessObject, PortalSettings portalSettings, int userID, string userName, EventLogType logType) => + this.AddLog(businessObject, (IPortalSettings)portalSettings, userID, userName, logType); + + /// + [DnnDeprecated(9, 8, 0, "Use Dependency Injection to resolve 'DotNetNuke.Abstractions.Logging.IEventLogger' instead")] + public partial void AddLog(object businessObject, IPortalSettings portalSettings, int userID, string userName, EventLogType logType) => + this.EventLogger.AddLog(businessObject, portalSettings, userID, userName, (Abstractions.Logging.EventLogType)logType); + + /// + [DnnDeprecated(9, 7, 0, "It has been replaced by the overload taking IPortalSettings")] + public partial void AddLog(object businessObject, PortalSettings portalSettings, int userID, string userName, string logType) => + this.AddLog(businessObject, (IPortalSettings)portalSettings, userID, userName, logType); + + /// + [DnnDeprecated(9, 8, 0, "Use Dependency Injection to resolve 'DotNetNuke.Abstractions.Logging.IEventLogger' instead")] + public partial void AddLog(object businessObject, IPortalSettings portalSettings, int userID, string userName, string logType) => + this.EventLogger.AddLog(businessObject, portalSettings, userID, userName, logType); + + /// + [DnnDeprecated(9, 8, 0, "Use Dependency Injection to resolve 'DotNetNuke.Abstractions.Logging.IEventLogger' instead")] + public partial void AddLog(LogInfo logInfo) => + this.EventLogger.AddLog(logInfo); + + /// + [DnnDeprecated(9, 8, 0, "Use Dependency Injection to resolve 'DotNetNuke.Abstractions.Logging.IEventLogConfigService' instead")] + public partial void AddLogType(string configFile, string fallbackConfigFile) => + this.EventLogConfigService.AddLogType(configFile, fallbackConfigFile); + + /// + [DnnDeprecated(9, 8, 0, "Use Dependency Injection to resolve 'DotNetNuke.Abstractions.Logging.IEventLogConfigService' instead")] + public partial void AddLogType(LogTypeInfo logType) => + this.EventLogConfigService.AddLogType(logType); + + /// + [DnnDeprecated(9, 8, 0, "Use Dependency Injection to resolve 'DotNetNuke.Abstractions.Logging.IEventLogConfigService' instead")] + public partial void AddLogTypeConfigInfo(LogTypeConfigInfo logTypeConfig) => + this.EventLogConfigService.AddLogTypeConfigInfo(logTypeConfig); + + /// + [DnnDeprecated(9, 8, 0, "Use Dependency Injection to resolve 'DotNetNuke.Abstractions.Logging.IEventLogService' instead")] + public partial void ClearLog() => + this.EventLogService.ClearLog(); + + /// + [DnnDeprecated(9, 8, 0, "Use Dependency Injection to resolve 'DotNetNuke.Abstractions.Logging.IEventLogService' instead")] + public partial void DeleteLog(LogInfo logInfo) => + this.EventLogService.DeleteLog(logInfo); + + /// + [DnnDeprecated(9, 8, 0, "Use Dependency Injection to resolve 'DotNetNuke.Abstractions.Logging.IEventLogConfigService' instead")] + public partial void DeleteLogType(LogTypeInfo logType) => + this.EventLogConfigService.DeleteLogType(logType); + + /// + [DnnDeprecated(9, 8, 0, "Use Dependency Injection to resolve 'DotNetNuke.Abstractions.Logging.IEventLogConfigService' instead")] + public partial void DeleteLogTypeConfigInfo(LogTypeConfigInfo logTypeConfig) => + this.EventLogConfigService.DeleteLogTypeConfigInfo(logTypeConfig); + + /// + [DnnDeprecated(9, 8, 0, "Use Dependency Injection to resolve 'DotNetNuke.Abstractions.Logging.IEventLogService' instead")] + public partial List GetLogs(int portalID, string logType, int pageSize, int pageIndex, ref int totalRecords) => + this.EventLogService.GetLogs(portalID, logType, pageSize, pageIndex, ref totalRecords).Cast().ToList(); + + /// + [DnnDeprecated(9, 8, 0, "Use Dependency Injection to resolve 'DotNetNuke.Abstractions.Logging.IEventLogConfigService' instead")] + public partial ArrayList GetLogTypeConfigInfo() => + LogController.Instance.GetLogTypeConfigInfo(); + + /// + [DnnDeprecated(9, 8, 0, "Use Dependency Injection to resolve 'DotNetNuke.Abstractions.Logging.IEventLogConfigService' instead")] + public partial LogTypeConfigInfo GetLogTypeConfigInfoByID(string id) => + (LogTypeConfigInfo)this.EventLogConfigService.GetLogTypeConfigInfoByID(id); + + /// + [DnnDeprecated(9, 8, 0, "Use Dependency Injection to resolve 'DotNetNuke.Abstractions.Logging.IEventLogConfigService' instead")] + public partial Dictionary GetLogTypeInfoDictionary() => + this.EventLogConfigService + .GetLogTypeInfoDictionary() + .ToDictionary(key => key.Key, value => (LogTypeInfo)value.Value); + + /// + [DnnDeprecated(9, 8, 0, "Use Dependency Injection to resolve 'DotNetNuke.Abstractions.Logging.IEventLogService.GetLog()' instead")] + public partial object GetSingleLog(LogInfo log, LoggingProvider.ReturnType returnType) => + LogController.Instance.GetSingleLog(log, returnType); + + /// + [DnnDeprecated(9, 8, 0, "Use Dependency Injection to resolve 'DotNetNuke.Abstractions.Logging.IEventLogService' instead")] + public partial void PurgeLogBuffer() => + this.EventLogService.PurgeLogBuffer(); + + /// + [DnnDeprecated(9, 8, 0, "Use Dependency Injection to resolve 'DotNetNuke.Abstractions.Logging.IEventLogConfigService' instead")] + public virtual partial void UpdateLogTypeConfigInfo(LogTypeConfigInfo logTypeConfig) => + this.EventLogConfigService.UpdateLogTypeConfigInfo(logTypeConfig); + + /// + [DnnDeprecated(9, 8, 0, "Use Dependency Injection to resolve 'DotNetNuke.Abstractions.Logging.IEventLogConfigService' instead")] + public virtual partial void UpdateLogType(LogTypeInfo logType) => + this.EventLogConfigService.UpdateLogType(logType); + + /// + [DnnDeprecated(9, 8, 0, "Use Dependency Injection to resolve 'DotNetNuke.Abstractions.Logging.IEventLogger' instead")] +#pragma warning disable CS0809 // Obsolete member overrides non-obsolete member + protected override partial Func GetFactory() => +#pragma warning restore CS0809 // Obsolete member overrides non-obsolete member + () => new EventLogController(); + } +#pragma warning restore SA1601 // Partial elements should be documented +#pragma warning restore SA1600 // Elements should be documented +} diff --git a/DNN Platform/Library/Obsolete/HostController.cs b/DNN Platform/Library/Obsolete/HostController.cs index 9dbd378518f..89c1aefe126 100644 --- a/DNN Platform/Library/Obsolete/HostController.cs +++ b/DNN Platform/Library/Obsolete/HostController.cs @@ -1,17 +1,17 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information - -namespace DotNetNuke.Entities.Controllers -{ - using System; - using System.Collections.Generic; - using System.Linq; - - using DotNetNuke.Abstractions.Application; - using DotNetNuke.Common; - using DotNetNuke.ComponentModel; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + +namespace DotNetNuke.Entities.Controllers +{ + using System; + using System.Collections.Generic; + using System.Linq; + + using DotNetNuke.Abstractions.Application; + using DotNetNuke.Common; + using DotNetNuke.ComponentModel; + using DotNetNuke.Internal.SourceGenerators; using Microsoft.Extensions.DependencyInjection; // None of the APIs are deprecated, but the IHostController @@ -19,46 +19,46 @@ namespace DotNetNuke.Entities.Controllers // it is time to remove APIs we should remove the parent // classes listed here - /// - public partial class HostController : ComponentBase, IHostController - { - [Obsolete("Deprecated in 9.7.1. Scheduled for removal in v11.0.0, use DotNetNuke.Abstractions.IHostSettingsService instead.")] - public static new IHostController Instance - { - get - { - var newHostController = Globals.DependencyProvider.GetRequiredService(); - return newHostController is IHostController castedController ? castedController : new HostController(); - } - } - - /// - [Obsolete("Deprecated in 9.7.1. Scheduled for removal in v11.0.0, use DotNetNuke.Abstractions.IHostSettingsService instead.")] - public Dictionary GetSettings() => - ((IHostSettingsService)this).GetSettings() - .Where(setting => setting.Value is ConfigurationSetting) - .Select(setting => new KeyValuePair(setting.Key, (ConfigurationSetting)setting.Value)) - .ToDictionary(setting => setting.Key, setting => setting.Value); - - /// - [Obsolete("Deprecated in 9.7.1. Scheduled for removal in v11.0.0, use DotNetNuke.Abstractions.IHostSettingsService instead.")] - public Dictionary GetSettingsDictionary() => - ((IHostSettingsService)this).GetSettingsDictionary() - .ToDictionary(setting => setting.Key, setting => setting.Value); - - /// - [Obsolete("Deprecated in 9.7.1. Scheduled for removal in v11.0.0, use DotNetNuke.Abstractions.IHostSettingsService instead.")] - public void Update(ConfigurationSetting config) => - ((IHostSettingsService)this).Update(config); - - /// - [Obsolete("Deprecated in 9.7.1. Scheduled for removal in v11.0.0, use DotNetNuke.Abstractions.IHostSettingsService instead.")] - public void Update(ConfigurationSetting config, bool clearCache) => - ((IHostSettingsService)this).Update(config, clearCache); - - /// - [Obsolete("Deprecated in 9.7.1. Scheduled for removal in v11.0.0, use DotNetNuke.Abstractions.IHostSettingsService instead.")] - public void Update(Dictionary settings) => - ((IHostSettingsService)this).Update(settings); - } -} + /// + public partial class HostController : ComponentBase, IHostController + { + [Obsolete("Deprecated in DotNetNuke 9.7.1. Use DotNetNuke.Abstractions.IHostSettingsService instead. Scheduled removal in v11.0.0.")] + public static new IHostController Instance + { + get + { + var newHostController = Globals.DependencyProvider.GetRequiredService(); + return newHostController is IHostController castedController ? castedController : new HostController(); + } + } + + /// + [DnnDeprecated(9, 7, 1, "use DotNetNuke.Abstractions.IHostSettingsService instead")] + public partial Dictionary GetSettings() => + ((IHostSettingsService)this).GetSettings() + .Where(setting => setting.Value is ConfigurationSetting) + .Select(setting => new KeyValuePair(setting.Key, (ConfigurationSetting)setting.Value)) + .ToDictionary(setting => setting.Key, setting => setting.Value); + + /// + [DnnDeprecated(9, 7, 1, "use DotNetNuke.Abstractions.IHostSettingsService instead")] + public partial Dictionary GetSettingsDictionary() => + ((IHostSettingsService)this).GetSettingsDictionary() + .ToDictionary(setting => setting.Key, setting => setting.Value); + + /// + [DnnDeprecated(9, 7, 1, "use DotNetNuke.Abstractions.IHostSettingsService instead")] + public partial void Update(ConfigurationSetting config) => + ((IHostSettingsService)this).Update(config); + + /// + [DnnDeprecated(9, 7, 1, "use DotNetNuke.Abstractions.IHostSettingsService instead")] + public partial void Update(ConfigurationSetting config, bool clearCache) => + ((IHostSettingsService)this).Update(config, clearCache); + + /// + [DnnDeprecated(9, 7, 1, "use DotNetNuke.Abstractions.IHostSettingsService instead")] + public partial void Update(Dictionary settings) => + ((IHostSettingsService)this).Update(settings); + } +} diff --git a/DNN Platform/Library/Obsolete/IModuleController.cs b/DNN Platform/Library/Obsolete/IModuleController.cs index 94fad831a5c..b85eb0315ec 100644 --- a/DNN Platform/Library/Obsolete/IModuleController.cs +++ b/DNN Platform/Library/Obsolete/IModuleController.cs @@ -2,37 +2,38 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information -namespace DotNetNuke.Entities.Modules.Internal -{ - using System; - using System.ComponentModel; +namespace DotNetNuke.Entities.Modules.Internal +{ + using System.ComponentModel; - /// - /// Do not implement. This interface is only implemented by the DotNetNuke core framework. Outside the framework it should used as a type and for unit test purposes only. - /// There is no guarantee that this interface will not change. - /// - [EditorBrowsable(EditorBrowsableState.Never)] - [Obsolete("This class has been obsoleted in 7.3.0 - please use version in DotNetNuke.Entities.Modules instead. Scheduled removal in v10.0.0.")] - public interface IModuleController - { - /// Gets the module. - /// The module ID. - /// The tab ID. - /// module info. - ModuleInfo GetModule(int moduleId, int tabId); - - /// Adds or updates a module's setting value. - /// ID of the tabmodule, the setting belongs to. - /// name of the setting property. - /// value of the setting (String). - /// Empty SettingValue will remove the setting. - void UpdateModuleSetting(int moduleId, string settingName, string settingValue); - - /// Adds or updates a tab module's setting value. - /// ID of the tabmodule, the setting belongs to. - /// name of the setting property. - /// value of the setting (String). - /// Empty SettingValue will remove the setting. - void UpdateTabModuleSetting(int tabModuleId, string settingName, string settingValue); - } -} + using DotNetNuke.Internal.SourceGenerators; + + /// + /// Do not implement. This interface is only implemented by the DotNetNuke core framework. Outside the framework it should used as a type and for unit test purposes only. + /// There is no guarantee that this interface will not change. + /// + [EditorBrowsable(EditorBrowsableState.Never)] + [DnnDeprecated(7, 3, 0, "Please use version in DotNetNuke.Entities.Modules instead", RemovalVersion = 10)] + public partial interface IModuleController + { + /// Gets the module. + /// The module ID. + /// The tab ID. + /// module info. + ModuleInfo GetModule(int moduleId, int tabId); + + /// Adds or updates a module's setting value. + /// ID of the tabmodule, the setting belongs to. + /// name of the setting property. + /// value of the setting (String). + /// Empty SettingValue will remove the setting. + void UpdateModuleSetting(int moduleId, string settingName, string settingValue); + + /// Adds or updates a tab module's setting value. + /// ID of the tabmodule, the setting belongs to. + /// name of the setting property. + /// value of the setting (String). + /// Empty SettingValue will remove the setting. + void UpdateTabModuleSetting(int tabModuleId, string settingName, string settingValue); + } +} diff --git a/DNN Platform/Library/Obsolete/IPortalAliasController.cs b/DNN Platform/Library/Obsolete/IPortalAliasController.cs index c20c3cf9255..e139a609d0e 100644 --- a/DNN Platform/Library/Obsolete/IPortalAliasController.cs +++ b/DNN Platform/Library/Obsolete/IPortalAliasController.cs @@ -2,45 +2,46 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information -namespace DotNetNuke.Entities.Portals.Internal -{ - using System; - using System.Collections.Generic; - using System.ComponentModel; - - /// - /// Do not implement. This interface is only implemented by the DotNetNuke core framework. Outside the framework it should used as a type and for unit test purposes only. - /// There is no guarantee that this interface will not change. - /// - [EditorBrowsable(EditorBrowsableState.Never)] - [Obsolete("This class has been obsoleted in 7.3.0 - please use version in DotNetNuke.Entities.Portals instead. Scheduled removal in v10.0.0.")] - public interface IPortalAliasController - { - /// Add a new Portal Alias. - /// The portal alias to add. - /// The Id of the newly added portal alias. - int AddPortalAlias(PortalAliasInfo portalAlias); - - /// Delete a Portal Alias. - /// The portal alias to remove. - void DeletePortalAlias(PortalAliasInfo portalAlias); - - /// Gets the portal alias info. - /// The portal alias. - /// Portal alias info. - PortalAliasInfo GetPortalAlias(string alias); - - /// Gets the portal alias by portal ID. - /// The portal ID. - /// Portal alias collection. - IEnumerable GetPortalAliasesByPortalId(int portalId); - - /// Gets all the portal aliases defined. - /// A dictionary keyed by the HTTP Alias. - IDictionary GetPortalAliases(); - - /// Updates the portal alias info. - /// The obj portal alias info. - void UpdatePortalAlias(PortalAliasInfo portalAlias); - } -} +namespace DotNetNuke.Entities.Portals.Internal +{ + using System.Collections.Generic; + using System.ComponentModel; + + using DotNetNuke.Internal.SourceGenerators; + + /// + /// Do not implement. This interface is only implemented by the DotNetNuke core framework. Outside the framework it should used as a type and for unit test purposes only. + /// There is no guarantee that this interface will not change. + /// + [EditorBrowsable(EditorBrowsableState.Never)] + [DnnDeprecated(7, 3, 0, "Please use version in DotNetNuke.Entities.Portals instead", RemovalVersion = 10)] + public partial interface IPortalAliasController + { + /// Add a new Portal Alias. + /// The portal alias to add. + /// The Id of the newly added portal alias. + int AddPortalAlias(PortalAliasInfo portalAlias); + + /// Delete a Portal Alias. + /// The portal alias to remove. + void DeletePortalAlias(PortalAliasInfo portalAlias); + + /// Gets the portal alias info. + /// The portal alias. + /// Portal alias info. + PortalAliasInfo GetPortalAlias(string alias); + + /// Gets the portal alias by portal ID. + /// The portal ID. + /// Portal alias collection. + IEnumerable GetPortalAliasesByPortalId(int portalId); + + /// Gets all the portal aliases defined. + /// A dictionary keyed by the HTTP Alias. + IDictionary GetPortalAliases(); + + /// Updates the portal alias info. + /// The obj portal alias info. + void UpdatePortalAlias(PortalAliasInfo portalAlias); + } +} diff --git a/DNN Platform/Library/Obsolete/IPortalSettings.cs b/DNN Platform/Library/Obsolete/IPortalSettings.cs index 58d74ab8d98..835b9d7cd62 100644 --- a/DNN Platform/Library/Obsolete/IPortalSettings.cs +++ b/DNN Platform/Library/Obsolete/IPortalSettings.cs @@ -2,15 +2,16 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information -namespace DotNetNuke.Entities.Portals.Internal -{ - using System; - using System.ComponentModel; +namespace DotNetNuke.Entities.Portals.Internal +{ + using System.ComponentModel; - [EditorBrowsable(EditorBrowsableState.Never)] - [Obsolete("Deprecated in DotNetNuke 7.3.0. Use PortalController.Instance.GetCurrentPortalSettings to get a mockable PortalSettings. Scheduled removal in v10.0.0.")] - public interface IPortalSettings - { - string AdministratorRoleName { get; } - } -} + using DotNetNuke.Internal.SourceGenerators; + + [EditorBrowsable(EditorBrowsableState.Never)] + [DnnDeprecated(7, 3, 0, "Use PortalController.Instance.GetCurrentPortalSettings to get a mockable PortalSettings", RemovalVersion = 10)] + public partial interface IPortalSettings + { + string AdministratorRoleName { get; } + } +} diff --git a/DNN Platform/Library/Obsolete/IRoleController.cs b/DNN Platform/Library/Obsolete/IRoleController.cs index 6099808083e..41719d68c0d 100644 --- a/DNN Platform/Library/Obsolete/IRoleController.cs +++ b/DNN Platform/Library/Obsolete/IRoleController.cs @@ -7,9 +7,11 @@ namespace DotNetNuke.Security.Roles.Internal using System.Collections.Generic; using System.ComponentModel; + using DotNetNuke.Internal.SourceGenerators; + [EditorBrowsable(EditorBrowsableState.Never)] - [Obsolete("This class has been obsoleted in 7.3.0 - please use version in DotNetNuke.Security.Roles instead. Scheduled removal in v10.0.0.")] - public interface IRoleController + [DnnDeprecated(7, 3, 0, "Please use version in DotNetNuke.Security.Roles instead", RemovalVersion = 10)] + public partial interface IRoleController { /// Adds a role. /// The Role to Add. diff --git a/DNN Platform/Library/Obsolete/ITabController.cs b/DNN Platform/Library/Obsolete/ITabController.cs index 4e006f2fca4..7f284d23dca 100644 --- a/DNN Platform/Library/Obsolete/ITabController.cs +++ b/DNN Platform/Library/Obsolete/ITabController.cs @@ -2,34 +2,35 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information -namespace DotNetNuke.Entities.Tabs.Internal -{ - using System; - using System.Collections.Generic; - using System.ComponentModel; - - /// - /// Do not implement. This interface is only implemented by the DotNetNuke core framework. Outside the framework it should used as a type and for unit test purposes only. - /// There is no guarantee that this interface will not change. - /// - [EditorBrowsable(EditorBrowsableState.Never)] - [Obsolete("This class has been obsoleted in 7.3.0 - please use version in DotNetNuke.Entities.Tabs instead. Scheduled removal in v10.0.0.")] - public interface ITabController - { - void DeleteTabUrl(TabUrlInfo tabUrl, int portalId, bool clearCache); - - /// Gets the tab. - /// The tab id. - /// The portal id. - /// tab info. - TabInfo GetTab(int tabId, int portalId); - - Dictionary GetCustomAliases(int tabId, int portalId); - - List GetAliasSkins(int tabId, int portalId); - - List GetTabUrls(int tabId, int portalId); - - void SaveTabUrl(TabUrlInfo tabUrl, int portalId, bool clearCache); - } -} +namespace DotNetNuke.Entities.Tabs.Internal +{ + using System.Collections.Generic; + using System.ComponentModel; + + using DotNetNuke.Internal.SourceGenerators; + + /// + /// Do not implement. This interface is only implemented by the DotNetNuke core framework. Outside the framework it should used as a type and for unit test purposes only. + /// There is no guarantee that this interface will not change. + /// + [EditorBrowsable(EditorBrowsableState.Never)] + [DnnDeprecated(7, 3, 0, "Please use version in DotNetNuke.Entities.Tabs instead", RemovalVersion = 10)] + public partial interface ITabController + { + void DeleteTabUrl(TabUrlInfo tabUrl, int portalId, bool clearCache); + + /// Gets the tab. + /// The tab id. + /// The portal id. + /// tab info. + TabInfo GetTab(int tabId, int portalId); + + Dictionary GetCustomAliases(int tabId, int portalId); + + List GetAliasSkins(int tabId, int portalId); + + List GetTabUrls(int tabId, int portalId); + + void SaveTabUrl(TabUrlInfo tabUrl, int portalId, bool clearCache); + } +} diff --git a/DNN Platform/Library/Obsolete/IUserController.cs b/DNN Platform/Library/Obsolete/IUserController.cs index 70dfe178b46..861c597d7d8 100644 --- a/DNN Platform/Library/Obsolete/IUserController.cs +++ b/DNN Platform/Library/Obsolete/IUserController.cs @@ -4,13 +4,14 @@ namespace DotNetNuke.Entities.Users.Internal { - using System; using System.Collections.Generic; using System.ComponentModel; + using DotNetNuke.Internal.SourceGenerators; + [EditorBrowsable(EditorBrowsableState.Never)] - [Obsolete("This class has been obsoleted in 7.3.0 - please use version in DotNetNuke.Entities.Users instead. Scheduled removal in v10.0.0.")] - public interface IUserController + [DnnDeprecated(7, 3, 0, "please use version in DotNetNuke.Entities.Users instead", RemovalVersion = 10)] + public partial interface IUserController { UserInfo GetUserByDisplayname(int portalId, string displayName); diff --git a/DNN Platform/Library/Obsolete/LogController.cs b/DNN Platform/Library/Obsolete/LogController.cs index 21363f472b6..a4b83349277 100644 --- a/DNN Platform/Library/Obsolete/LogController.cs +++ b/DNN Platform/Library/Obsolete/LogController.cs @@ -1,32 +1,33 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information -namespace DotNetNuke.Services.Log.EventLog -{ - using System; - using System.ComponentModel; +namespace DotNetNuke.Services.Log.EventLog +{ + using System.ComponentModel; - public partial class LogController - { - [EditorBrowsable(EditorBrowsableState.Never)] - [Obsolete("Deprecated in 7.3. Use GetLogTypeInfo and use the LoggingIsActive property.. Scheduled removal in v10.0.0.")] - public bool LoggingIsEnabled(string logType, int portalID) - { - return LoggingProvider.Instance().LoggingIsEnabled(logType, portalID); - } - - [EditorBrowsable(EditorBrowsableState.Never)] - [Obsolete("Deprecated in 7.3. Use LoggingProvider.Instance().SupportsEmailNotification().. Scheduled removal in v10.0.0.")] - public virtual bool SupportsEmailNotification() - { - return LoggingProvider.Instance().SupportsEmailNotification(); - } - - [EditorBrowsable(EditorBrowsableState.Never)] - [Obsolete("Deprecated in 7.3. Use LoggingProvider.Instance().SupportsInternalViewer().. Scheduled removal in v10.0.0.")] - public virtual bool SupportsInternalViewer() - { - return LoggingProvider.Instance().SupportsInternalViewer(); - } - } -} + using DotNetNuke.Internal.SourceGenerators; + + public partial class LogController + { + [EditorBrowsable(EditorBrowsableState.Never)] + [DnnDeprecated(7, 3, 0, "Use GetLogTypeInfo and use the LoggingIsActive property.", RemovalVersion = 10)] + public partial bool LoggingIsEnabled(string logType, int portalID) + { + return LoggingProvider.Instance().LoggingIsEnabled(logType, portalID); + } + + [EditorBrowsable(EditorBrowsableState.Never)] + [DnnDeprecated(7, 3, 0, "Use LoggingProvider.Instance().SupportsEmailNotification().", RemovalVersion = 10)] + public virtual partial bool SupportsEmailNotification() + { + return LoggingProvider.Instance().SupportsEmailNotification(); + } + + [EditorBrowsable(EditorBrowsableState.Never)] + [DnnDeprecated(7, 3, 0, "Use LoggingProvider.Instance().SupportsInternalViewer().", RemovalVersion = 10)] + public virtual partial bool SupportsInternalViewer() + { + return LoggingProvider.Instance().SupportsInternalViewer(); + } + } +} diff --git a/DNN Platform/Library/Obsolete/LogInfo.cs b/DNN Platform/Library/Obsolete/LogInfo.cs index 2ab95cc80c8..3721bbbf4ee 100644 --- a/DNN Platform/Library/Obsolete/LogInfo.cs +++ b/DNN Platform/Library/Obsolete/LogInfo.cs @@ -9,42 +9,42 @@ namespace DotNetNuke.Services.Log.EventLog public partial class LogInfo { - [Obsolete("Deprecated in 9.8.0. Use 'DotNetNuke.Abstractions.Logging.ILogInfo.LogGuid' instead. Scheduled for removal in v11.0.0.")] + [Obsolete("Deprecated in DotNetNuke 9.8.0. Use 'DotNetNuke.Abstractions.Logging.ILogInfo.LogGuid' instead. Scheduled removal in v11.0.0.")] public string LogGUID { get => ((ILogInfo)this).LogGuid; set => ((ILogInfo)this).LogGuid = value; } - [Obsolete("Deprecated in 9.8.0. Use 'DotNetNuke.Abstractions.Logging.ILogInfo.LogFileId' instead. Scheduled for removal in v11.0.0.")] + [Obsolete("Deprecated in DotNetNuke 9.8.0. Use 'DotNetNuke.Abstractions.Logging.ILogInfo.LogFileId' instead. Scheduled removal in v11.0.0.")] public string LogFileID { get => ((ILogInfo)this).LogFileId; set => ((ILogInfo)this).LogFileId = value; } - [Obsolete("Deprecated in 9.8.0. Use 'DotNetNuke.Abstractions.Logging.ILogInfo.LogUserId' instead. Scheduled for removal in v11.0.0.")] + [Obsolete("Deprecated in DotNetNuke 9.8.0. Use 'DotNetNuke.Abstractions.Logging.ILogInfo.LogUserId' instead. Scheduled removal in v11.0.0.")] public int LogUserID { get => ((ILogInfo)this).LogUserId; set => ((ILogInfo)this).LogUserId = value; } - [Obsolete("Deprecated in 9.8.0. Use 'DotNetNuke.Abstractions.Logging.ILogInfo.LogEventId' instead. Scheduled for removal in v11.0.0.")] + [Obsolete("Deprecated in DotNetNuke 9.8.0. Use 'DotNetNuke.Abstractions.Logging.ILogInfo.LogEventId' instead. Scheduled removal in v11.0.0.")] public int LogEventID { get => ((ILogInfo)this).LogEventId; set => ((ILogInfo)this).LogEventId = value; } - [Obsolete("Deprecated in 9.8.0. Use 'DotNetNuke.Abstractions.Logging.ILogInfo.LogPortalId' instead. Scheduled for removal in v11.0.0.")] + [Obsolete("Deprecated in DotNetNuke 9.8.0. Use 'DotNetNuke.Abstractions.Logging.ILogInfo.LogPortalId' instead. Scheduled removal in v11.0.0.")] public int LogPortalID { get => ((ILogInfo)this).LogPortalId; set => ((ILogInfo)this).LogPortalId = value; } - [Obsolete("Deprecated in 9.8.0. Use 'DotNetNuke.Abstractions.Logging.ILogInfo.LogConfigId' instead. Scheduled for removal in v11.0.0.")] + [Obsolete("Deprecated in DotNetNuke 9.8.0. Use 'DotNetNuke.Abstractions.Logging.ILogInfo.LogConfigId' instead. Scheduled removal in v11.0.0.")] public string LogConfigID { get => ((ILogInfo)this).LogConfigId; diff --git a/DNN Platform/Library/Obsolete/LogTypeConfigInfo.cs b/DNN Platform/Library/Obsolete/LogTypeConfigInfo.cs index d51df897240..bb6dbfff1b3 100644 --- a/DNN Platform/Library/Obsolete/LogTypeConfigInfo.cs +++ b/DNN Platform/Library/Obsolete/LogTypeConfigInfo.cs @@ -9,14 +9,14 @@ namespace DotNetNuke.Services.Log.EventLog public partial class LogTypeConfigInfo { - [Obsolete("Deprecated in 9.8.0. Use 'DotNetNuke.Abstractions.Logging.ILogTypeConfigInfo.Id' instead. Scheduled for removal in v11.0.0.")] + [Obsolete("Deprecated in DotNetNuke 9.8.0. Use 'DotNetNuke.Abstractions.Logging.ILogTypeConfigInfo.Id' instead. Scheduled removal in v11.0.0.")] public string ID { get => ((ILogTypeConfigInfo)this).Id; set => ((ILogTypeConfigInfo)this).Id = value; } - [Obsolete("Deprecated in 9.8.0. Use 'DotNetNuke.Abstractions.Logging.ILogTypeConfigInfo.LogTypePortalId' instead. Scheduled for removal in v11.0.0.")] + [Obsolete("Deprecated in DotNetNuke 9.8.0. Use 'DotNetNuke.Abstractions.Logging.ILogTypeConfigInfo.LogTypePortalId' instead. Scheduled removal in v11.0.0.")] public string LogTypePortalID { get => ((ILogTypeConfigInfo)this).LogTypePortalId; diff --git a/DNN Platform/Library/Obsolete/LogTypeInfo.cs b/DNN Platform/Library/Obsolete/LogTypeInfo.cs index c6deaa56715..d49de0a5e56 100644 --- a/DNN Platform/Library/Obsolete/LogTypeInfo.cs +++ b/DNN Platform/Library/Obsolete/LogTypeInfo.cs @@ -9,7 +9,7 @@ namespace DotNetNuke.Services.Log.EventLog public partial class LogTypeInfo { - [Obsolete("Deprecated in 9.8.0. Use 'DotNetNuke.Abstractions.Logging.ILogTypeInfo.LogTypeCssClass' instead. Scheduled for removal in v11.0.0.")] + [Obsolete("Deprecated in DotNetNuke 9.8.0. Use 'DotNetNuke.Abstractions.Logging.ILogTypeInfo.LogTypeCssClass' instead. Scheduled removal in v11.0.0.")] public string LogTypeCSSClass { get => ((ILogTypeInfo)this).LogTypeCssClass; diff --git a/DNN Platform/Library/Obsolete/ModuleController.cs b/DNN Platform/Library/Obsolete/ModuleController.cs index 87ec1d33ca0..9be5f744b9b 100644 --- a/DNN Platform/Library/Obsolete/ModuleController.cs +++ b/DNN Platform/Library/Obsolete/ModuleController.cs @@ -1,144 +1,145 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information -namespace DotNetNuke.Entities.Modules -{ - using System; - using System.Collections; - using System.Collections.Generic; - using System.ComponentModel; - using System.Data; - using System.Linq; +namespace DotNetNuke.Entities.Modules +{ + using System; + using System.Collections; + using System.Collections.Generic; + using System.ComponentModel; + using System.Data; + using System.Linq; - using DotNetNuke.Common.Utilities; - using DotNetNuke.Entities.Portals; - using DotNetNuke.Entities.Tabs; - using DotNetNuke.Entities.Users; - using DotNetNuke.Services.Exceptions; - using DotNetNuke.Services.Log.EventLog; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Tabs; + using DotNetNuke.Entities.Users; + using DotNetNuke.Internal.SourceGenerators; + using DotNetNuke.Services.Exceptions; + using DotNetNuke.Services.Log.EventLog; - public partial class ModuleController - { - [EditorBrowsable(EditorBrowsableState.Never)] - [Obsolete("Deprecated in DotNetNuke 7.3. No longer neccessary. Scheduled removal in v10.0.0.")] - public void CopyTabModuleSettings(ModuleInfo fromModule, ModuleInfo toModule) - { - this.CopyTabModuleSettingsInternal(fromModule, toModule); - } - - [EditorBrowsable(EditorBrowsableState.Never)] - [Obsolete("Deprecated in DNN 7.3. Use an alternate overload. Scheduled removal in v10.0.0.")] - public void DeleteAllModules(int moduleId, int tabId, List fromTabs) - { - this.DeleteAllModules(moduleId, tabId, fromTabs, true, false, false); - } - - [EditorBrowsable(EditorBrowsableState.Never)] - [Obsolete("Deprecated in DNN 7.3. Scheduled removal in v10.0.0.")] - public void DeleteModuleSettings(int moduleId) - { - DataProvider.DeleteModuleSettings(moduleId); - var log = new LogInfo { LogTypeKey = EventLogController.EventLogType.MODULE_SETTING_DELETED.ToString() }; - log.LogProperties.Add(new LogDetailInfo("ModuleId", moduleId.ToString())); - LogController.Instance.AddLog(log); - this.UpdateTabModuleVersionsByModuleID(moduleId); - ClearModuleSettingsCache(moduleId); - } - - [EditorBrowsable(EditorBrowsableState.Never)] - [Obsolete("Deprecated in DNN 7.3. Scheduled removal in v10.0.0.")] - public void DeleteTabModuleSettings(int tabModuleId) - { - DataProvider.DeleteTabModuleSettings(tabModuleId); - UpdateTabModuleVersion(tabModuleId); - EventLogController.Instance.AddLog( - "TabModuleID", - tabModuleId.ToString(), - PortalController.Instance.GetCurrentPortalSettings(), - UserController.Instance.GetCurrentUserInfo().UserID, - EventLogController.EventLogType.TABMODULE_SETTING_DELETED); - ClearTabModuleSettingsCache(tabModuleId, null); - } - - [EditorBrowsable(EditorBrowsableState.Never)] - [Obsolete("Deprecated in DNN 7.3. Please use the ModuleSettings property of the ModuleInfo object. Scheduled removal in v10.0.0.")] - public Hashtable GetModuleSettings(int moduleId) - { - var settings = new Hashtable(); - IDataReader dr = null; - try - { - dr = DataProvider.GetModuleSettings(moduleId); - while (dr.Read()) - { - if (!dr.IsDBNull(1)) - { - settings[dr.GetString(0)] = dr.GetString(1); - } - else - { - settings[dr.GetString(0)] = string.Empty; - } - } - } - catch (Exception ex) - { - Exceptions.LogException(ex); - } - finally - { - // Ensure DataReader is closed - CBO.CloseDataReader(dr, true); - } - - return settings; - } - - [EditorBrowsable(EditorBrowsableState.Never)] - [Obsolete("Deprecated in DNN 7.3. Replaced by GetTabModulesByModule(moduleID). Scheduled removal in v10.0.0.")] - public ArrayList GetModuleTabs(int moduleID) - { - return new ArrayList(this.GetTabModulesByModule(moduleID).ToArray()); - } - - [EditorBrowsable(EditorBrowsableState.Never)] - [Obsolete("Deprecated in DNN 7.3. Replaced by GetModules(portalId). Scheduled removal in v10.0.0.")] - public ArrayList GetRecycleModules(int portalID) - { - return this.GetModules(portalID); - } - - [EditorBrowsable(EditorBrowsableState.Never)] - [Obsolete("Deprecated in DNN 7.3. Please use the TabModuleSettings property of the ModuleInfo object. Scheduled removal in v10.0.0.")] - public Hashtable GetTabModuleSettings(int tabModuleId) - { - var settings = new Hashtable(); - IDataReader dr = null; - try - { - dr = DataProvider.GetTabModuleSettings(tabModuleId); - while (dr.Read()) - { - if (!dr.IsDBNull(1)) - { - settings[dr.GetString(0)] = dr.GetString(1); - } - else - { - settings[dr.GetString(0)] = string.Empty; - } - } - } - catch (Exception ex) - { - Exceptions.LogException(ex); - } - finally - { - CBO.CloseDataReader(dr, true); - } - - return settings; - } - } -} + public partial class ModuleController + { + [EditorBrowsable(EditorBrowsableState.Never)] + [DnnDeprecated(7, 3, 0, "No longer necessary", RemovalVersion = 10)] + public partial void CopyTabModuleSettings(ModuleInfo fromModule, ModuleInfo toModule) + { + this.CopyTabModuleSettingsInternal(fromModule, toModule); + } + + [EditorBrowsable(EditorBrowsableState.Never)] + [DnnDeprecated(7, 3, 0, "Use an alternate overload", RemovalVersion = 10)] + public partial void DeleteAllModules(int moduleId, int tabId, List fromTabs) + { + this.DeleteAllModules(moduleId, tabId, fromTabs, true, false, false); + } + + [EditorBrowsable(EditorBrowsableState.Never)] + [DnnDeprecated(7, 3, 0, "No replacement", RemovalVersion = 10)] + public partial void DeleteModuleSettings(int moduleId) + { + DataProvider.DeleteModuleSettings(moduleId); + var log = new LogInfo { LogTypeKey = EventLogController.EventLogType.MODULE_SETTING_DELETED.ToString() }; + log.LogProperties.Add(new LogDetailInfo("ModuleId", moduleId.ToString())); + LogController.Instance.AddLog(log); + this.UpdateTabModuleVersionsByModuleID(moduleId); + ClearModuleSettingsCache(moduleId); + } + + [EditorBrowsable(EditorBrowsableState.Never)] + [DnnDeprecated(7, 3, 0, "No replacement", RemovalVersion = 10)] + public partial void DeleteTabModuleSettings(int tabModuleId) + { + DataProvider.DeleteTabModuleSettings(tabModuleId); + UpdateTabModuleVersion(tabModuleId); + EventLogController.Instance.AddLog( + "TabModuleID", + tabModuleId.ToString(), + PortalController.Instance.GetCurrentPortalSettings(), + UserController.Instance.GetCurrentUserInfo().UserID, + EventLogController.EventLogType.TABMODULE_SETTING_DELETED); + ClearTabModuleSettingsCache(tabModuleId, null); + } + + [EditorBrowsable(EditorBrowsableState.Never)] + [DnnDeprecated(7, 3, 0, "Please use the ModuleSettings property of the ModuleInfo object", RemovalVersion = 10)] + public partial Hashtable GetModuleSettings(int moduleId) + { + var settings = new Hashtable(); + IDataReader dr = null; + try + { + dr = DataProvider.GetModuleSettings(moduleId); + while (dr.Read()) + { + if (!dr.IsDBNull(1)) + { + settings[dr.GetString(0)] = dr.GetString(1); + } + else + { + settings[dr.GetString(0)] = string.Empty; + } + } + } + catch (Exception ex) + { + Exceptions.LogException(ex); + } + finally + { + // Ensure DataReader is closed + CBO.CloseDataReader(dr, true); + } + + return settings; + } + + [EditorBrowsable(EditorBrowsableState.Never)] + [DnnDeprecated(7, 3, 0, "Replaced by GetTabModulesByModule(moduleID)", RemovalVersion = 10)] + public partial ArrayList GetModuleTabs(int moduleID) + { + return new ArrayList(this.GetTabModulesByModule(moduleID).ToArray()); + } + + [EditorBrowsable(EditorBrowsableState.Never)] + [DnnDeprecated(7, 3, 0, "Replaced by GetModules(portalId)", RemovalVersion = 10)] + public partial ArrayList GetRecycleModules(int portalID) + { + return this.GetModules(portalID); + } + + [EditorBrowsable(EditorBrowsableState.Never)] + [DnnDeprecated(7, 3, 0, "Please use the TabModuleSettings property of the ModuleInfo object", RemovalVersion = 10)] + public partial Hashtable GetTabModuleSettings(int tabModuleId) + { + var settings = new Hashtable(); + IDataReader dr = null; + try + { + dr = DataProvider.GetTabModuleSettings(tabModuleId); + while (dr.Read()) + { + if (!dr.IsDBNull(1)) + { + settings[dr.GetString(0)] = dr.GetString(1); + } + else + { + settings[dr.GetString(0)] = string.Empty; + } + } + } + catch (Exception ex) + { + Exceptions.LogException(ex); + } + finally + { + CBO.CloseDataReader(dr, true); + } + + return settings; + } + } +} diff --git a/DNN Platform/Library/Obsolete/PortalAliasController.cs b/DNN Platform/Library/Obsolete/PortalAliasController.cs index ed59dd36736..1c9e1274c19 100644 --- a/DNN Platform/Library/Obsolete/PortalAliasController.cs +++ b/DNN Platform/Library/Obsolete/PortalAliasController.cs @@ -17,13 +17,14 @@ namespace DotNetNuke.Entities.Portals using DotNetNuke.Data; using DotNetNuke.Entities.Users; using DotNetNuke.Framework; + using DotNetNuke.Internal.SourceGenerators; using DotNetNuke.Services.Log.EventLog; using Microsoft.Extensions.DependencyInjection; public partial class PortalAliasController : ServiceLocator, IPortalAliasController { - [Obsolete("Deprecated in 9.7.2. Scheduled for removal in v11.0.0, use DotNetNuke.Abstractions.Portals.IPortalAliasService via dependency injection instead.")] + [Obsolete("Deprecated in DotNetNuke 9.7.2. Use DotNetNuke.Abstractions.Portals.IPortalAliasService via dependency injection instead. Scheduled removal in v11.0.0.")] public static new IPortalAliasController Instance { @@ -35,15 +36,15 @@ public partial class PortalAliasController : ServiceLocatorThe portal id. /// The portal alias. /// Portal alias. - [Obsolete("Deprecated in 9.7.2. Scheduled for removal in v11.0.0, use DotNetNuke.Abstractions.Portals.IPortalAliasService via dependency injection instead.")] - public static string GetPortalAliasByPortal(int portalId, string portalAlias) => + [DnnDeprecated(9, 7, 2, "use DotNetNuke.Abstractions.Portals.IPortalAliasService via dependency injection instead")] + public static partial string GetPortalAliasByPortal(int portalId, string portalAlias) => ((IPortalAliasService)Instance).GetPortalAliasByPortal(portalId, portalAlias); /// Gets the portal alias by tab. /// The tab ID. /// The portal alias. /// Portal alias. - [Obsolete("Deprecated in 9.7.2. Scheduled for removal in v11.0.0, use DotNetNuke.Abstractions.Portals.IPortalAliasService via dependency injection instead.")] - public static string GetPortalAliasByTab(int tabId, string portalAlias) => + [DnnDeprecated(9, 7, 2, "use DotNetNuke.Abstractions.Portals.IPortalAliasService via dependency injection instead")] + public static partial string GetPortalAliasByTab(int tabId, string portalAlias) => ((IPortalAliasService)Instance).GetPortalAliasByTab(tabId, portalAlias); /// Validates the alias. /// The portal alias. /// if set to true [ischild]. /// true if the alias is a valid url format; otherwise return false. - [Obsolete("Deprecated in 9.7.2. Scheduled for removal in v11.0.0, use DotNetNuke.Abstractions.Portals.IPortalAliasService via dependency injection instead.")] - public static bool ValidateAlias(string portalAlias, bool ischild) => + [DnnDeprecated(9, 7, 2, "use DotNetNuke.Abstractions.Portals.IPortalAliasService via dependency injection instead")] + public static partial bool ValidateAlias(string portalAlias, bool ischild) => ((IPortalAliasService)Instance).ValidateAlias(portalAlias, ischild); [EditorBrowsable(EditorBrowsableState.Never)] - [Obsolete("Deprecated in version 7.1. Replaced by PortalAliasController.Instance.DeletePortalAlias. Scheduled removal in v10.0.0.")] - public void DeletePortalAlias(int portalAliasId) + [DnnDeprecated(7, 1, 0, "Replaced by PortalAliasController.Instance.DeletePortalAlias", RemovalVersion = 10)] + public partial void DeletePortalAlias(int portalAliasId) { DataProvider.Instance().DeletePortalAlias(portalAliasId); @@ -103,15 +104,15 @@ public void DeletePortalAlias(int portalAliasId) } [EditorBrowsable(EditorBrowsableState.Never)] - [Obsolete("Deprecated in version 7.1. Replaced by PortalAliasController.Instance.GetPortalAliasesByPortalId. Scheduled removal in v10.0.0.")] - public ArrayList GetPortalAliasArrayByPortalID(int portalID) + [DnnDeprecated(7, 1, 0, "Replaced by PortalAliasController.Instance.GetPortalAliasesByPortalId", RemovalVersion = 10)] + public partial ArrayList GetPortalAliasArrayByPortalID(int portalID) { return new ArrayList(Instance.GetPortalAliasesByPortalId(portalID).ToArray()); } [EditorBrowsable(EditorBrowsableState.Never)] - [Obsolete("Deprecated in version 7.1. Replaced by PortalAliasController.Instance.GetPortalAliasesByPortalId. Scheduled removal in v10.0.0.")] - public PortalAliasCollection GetPortalAliasByPortalID(int portalID) + [DnnDeprecated(7, 1, 0, "Replaced by PortalAliasController.Instance.GetPortalAliasesByPortalId", RemovalVersion = 10)] + public partial PortalAliasCollection GetPortalAliasByPortalID(int portalID) { var portalAliasCollection = new PortalAliasCollection(); @@ -124,45 +125,45 @@ public PortalAliasCollection GetPortalAliasByPortalID(int portalID) } [EditorBrowsable(EditorBrowsableState.Never)] - [Obsolete("Deprecated in version 7.1. Replaced by PortalAliasController.Instance.UpdatePortalAlias. Scheduled removal in v10.0.0.")] - public void UpdatePortalAliasInfo(PortalAliasInfo portalAlias) + [DnnDeprecated(7, 1, 0, "Replaced by PortalAliasController.Instance.UpdatePortalAlias", RemovalVersion = 10)] + public partial void UpdatePortalAliasInfo(PortalAliasInfo portalAlias) { Instance.UpdatePortalAlias(portalAlias); } - /// - [Obsolete("Deprecated in 9.7.2. Scheduled for removal in v11.0.0, use DotNetNuke.Abstractions.Portals.IPortalAliasService via dependency injection instead.")] - public int AddPortalAlias(PortalAliasInfo portalAlias) => + /// + [DnnDeprecated(9, 7, 2, "use DotNetNuke.Abstractions.Portals.IPortalAliasService via dependency injection instead")] + public partial int AddPortalAlias(PortalAliasInfo portalAlias) => ((IPortalAliasService)this).AddPortalAlias(portalAlias); - /// - [Obsolete("Deprecated in 9.7.2. Scheduled for removal in v11.0.0, use DotNetNuke.Abstractions.Portals.IPortalAliasService via dependency injection instead.")] - public void DeletePortalAlias(PortalAliasInfo portalAlias) => + /// + [DnnDeprecated(9, 7, 2, "use DotNetNuke.Abstractions.Portals.IPortalAliasService via dependency injection instead")] + public partial void DeletePortalAlias(PortalAliasInfo portalAlias) => ((IPortalAliasService)this).DeletePortalAlias(portalAlias); - /// - [Obsolete("Deprecated in 9.7.2. Scheduled for removal in v11.0.0, use DotNetNuke.Abstractions.Portals.IPortalAliasService via dependency injection instead.")] - public PortalAliasInfo GetPortalAlias(string alias) => + /// + [DnnDeprecated(9, 7, 2, "use DotNetNuke.Abstractions.Portals.IPortalAliasService via dependency injection instead")] + public partial PortalAliasInfo GetPortalAlias(string alias) => (PortalAliasInfo)((IPortalAliasService)this).GetPortalAlias(alias); /// Gets the portal alias. /// The portal alias. /// The portal ID. /// Portal Alias Info. - [Obsolete("Deprecated in 9.7.2. Scheduled for removal in v11.0.0, use DotNetNuke.Abstractions.Portals.IPortalAliasService via dependency injection instead.")] - public PortalAliasInfo GetPortalAlias(string alias, int portalId) => + [DnnDeprecated(9, 7, 2, "use DotNetNuke.Abstractions.Portals.IPortalAliasService via dependency injection instead")] + public partial PortalAliasInfo GetPortalAlias(string alias, int portalId) => (PortalAliasInfo)((IPortalAliasService)this).GetPortalAlias(alias, portalId); /// Gets the portal alias by portal alias ID. /// The portal alias ID. /// Portal alias info. - [Obsolete("Deprecated in 9.7.2. Scheduled for removal in v11.0.0, use DotNetNuke.Abstractions.Portals.IPortalAliasService via dependency injection instead.")] - public PortalAliasInfo GetPortalAliasByPortalAliasID(int portalAliasId) => + [DnnDeprecated(9, 7, 2, "use DotNetNuke.Abstractions.Portals.IPortalAliasService via dependency injection instead")] + public partial PortalAliasInfo GetPortalAliasByPortalAliasID(int portalAliasId) => (PortalAliasInfo)((IPortalAliasService)this).GetPortalAliasByPortalAliasId(portalAliasId); - /// - [Obsolete("Deprecated in 9.7.2. Scheduled for removal in v11.0.0, use DotNetNuke.Abstractions.Portals.IPortalAliasService via dependency injection instead.")] - public PortalAliasCollection GetPortalAliases() + /// + [DnnDeprecated(9, 7, 2, "use DotNetNuke.Abstractions.Portals.IPortalAliasService via dependency injection instead")] + public partial PortalAliasCollection GetPortalAliases() { var aliasCollection = new PortalAliasCollection(); foreach (var alias in this.GetPortalAliasesInternal().Values) @@ -173,22 +174,22 @@ public PortalAliasCollection GetPortalAliases() return aliasCollection; } - /// - [Obsolete("Deprecated in 9.7.2. Scheduled for removal in v11.0.0, use DotNetNuke.Abstractions.Portals.IPortalAliasService via dependency injection instead.")] - public IEnumerable GetPortalAliasesByPortalId(int portalId) => + /// + [DnnDeprecated(9, 7, 2, "use DotNetNuke.Abstractions.Portals.IPortalAliasService via dependency injection instead")] + public partial IEnumerable GetPortalAliasesByPortalId(int portalId) => ((IPortalAliasService)this).GetPortalAliasesByPortalId(portalId) .Cast(); /// Gets the portal by portal alias ID. /// The portal alias id. /// Portal info. - [Obsolete("Deprecated in 9.7.2. Scheduled for removal in v11.0.0, use DotNetNuke.Abstractions.Portals.IPortalAliasService via dependency injection instead.")] - public PortalInfo GetPortalByPortalAliasID(int portalAliasId) => + [DnnDeprecated(9, 7, 2, "use DotNetNuke.Abstractions.Portals.IPortalAliasService via dependency injection instead")] + public partial PortalInfo GetPortalByPortalAliasID(int portalAliasId) => (PortalInfo)((IPortalAliasService)this).GetPortalByPortalAliasId(portalAliasId); - /// - [Obsolete("Deprecated in 9.7.2. Scheduled for removal in v11.0.0, use DotNetNuke.Abstractions.Portals.IPortalAliasService via dependency injection instead.")] - public void UpdatePortalAlias(PortalAliasInfo portalAlias) => + /// + [DnnDeprecated(9, 7, 2, "use DotNetNuke.Abstractions.Portals.IPortalAliasService via dependency injection instead")] + public partial void UpdatePortalAlias(PortalAliasInfo portalAlias) => ((IPortalAliasService)this).UpdatePortalAlias(portalAlias); } } diff --git a/DNN Platform/Library/Obsolete/PortalController.cs b/DNN Platform/Library/Obsolete/PortalController.cs index 3cd5780adef..168ba6a3630 100644 --- a/DNN Platform/Library/Obsolete/PortalController.cs +++ b/DNN Platform/Library/Obsolete/PortalController.cs @@ -7,7 +7,6 @@ // ReSharper disable once CheckNamespace namespace DotNetNuke.Entities.Portals { - using System; using System.Collections.Generic; using System.ComponentModel; using System.IO; @@ -16,6 +15,7 @@ namespace DotNetNuke.Entities.Portals using DotNetNuke.Data; using DotNetNuke.Entities.Portals.Templates; using DotNetNuke.Entities.Users; + using DotNetNuke.Internal.SourceGenerators; using DotNetNuke.Services.Localization; using DotNetNuke.Services.Log.EventLog; @@ -27,22 +27,22 @@ namespace DotNetNuke.Entities.Portals public partial class PortalController { [EditorBrowsable(EditorBrowsableState.Never)] - [Obsolete("Deprecated in DotNetNuke 7.3. Replaced by PortalController.Instance.GetCurrentPortalSettings. Scheduled removal in v10.0.0.")] - public static PortalSettings GetCurrentPortalSettings() + [DnnDeprecated(7, 3, 0, "Replaced by PortalController.Instance.GetCurrentPortalSettings", RemovalVersion = 10)] + public static partial PortalSettings GetCurrentPortalSettings() { return GetCurrentPortalSettingsInternal(); } [EditorBrowsable(EditorBrowsableState.Never)] - [Obsolete("Deprecated in DNN 7.4.0. Replaced by PortalController.Instance.GetPortalSettings. Scheduled removal in v10.0.0.")] - public static Dictionary GetPortalSettingsDictionary(int portalId) + [DnnDeprecated(7, 4, 0, "Replaced by PortalController.Instance.GetPortalSettings", RemovalVersion = 10)] + public static partial Dictionary GetPortalSettingsDictionary(int portalId) { return Instance.GetPortalSettings(portalId); } [EditorBrowsable(EditorBrowsableState.Never)] - [Obsolete("Deprecated in DotNetNuke 7.3.0. Use one of the alternate overloads. Scheduled removal in v10.0.0.")] - public int CreatePortal(string portalName, string firstName, string lastName, string username, string password, string email, string description, string keyWords, string templatePath, string templateFile, string homeDirectory, string portalAlias, string serverPath, string childPath, bool isChildPortal) + [DnnDeprecated(7, 3, 0, "Use one of the alternate overloads", RemovalVersion = 10)] + public partial int CreatePortal(string portalName, string firstName, string lastName, string username, string password, string email, string description, string keyWords, string templatePath, string templateFile, string homeDirectory, string portalAlias, string serverPath, string childPath, bool isChildPortal) { var adminUser = new UserInfo { @@ -61,8 +61,8 @@ public int CreatePortal(string portalName, string firstName, string lastName, st } [EditorBrowsable(EditorBrowsableState.Never)] - [Obsolete("Deprecated in DotNetNuke 7.3.0. Use one of the alternate overloads. Scheduled removal in v10.0.0.")] - public int CreatePortal(string portalName, UserInfo adminUser, string description, string keyWords, string templatePath, string templateFile, string homeDirectory, string portalAlias, string serverPath, string childPath, bool isChildPortal) + [DnnDeprecated(7, 3, 0, "Use one of the alternate overloads", RemovalVersion = 10)] + public partial int CreatePortal(string portalName, UserInfo adminUser, string description, string keyWords, string templatePath, string templateFile, string homeDirectory, string portalAlias, string serverPath, string childPath, bool isChildPortal) { var template = PortalTemplateController.Instance.GetPortalTemplate(Path.Combine(templatePath, templateFile), null); @@ -70,8 +70,8 @@ public int CreatePortal(string portalName, UserInfo adminUser, string descriptio } [EditorBrowsable(EditorBrowsableState.Never)] - [Obsolete("Deprecated in DotNetNuke 7.3.0. Scheduled removal in v10.0.0.")] - public void DeletePortalInfo(int portalId) + [DnnDeprecated(7, 3, 0, "0", RemovalVersion = 10)] + public partial void DeletePortalInfo(int portalId) { UserController.DeleteUsers(portalId, false, true); @@ -83,31 +83,31 @@ public void DeletePortalInfo(int portalId) } [EditorBrowsable(EditorBrowsableState.Never)] - [Obsolete("Deprecated in DotNetNuke 7.3.0. Use one of the alternate overloads. Scheduled removal in v10.0.0.")] - public void ParseTemplate(int portalId, string templatePath, string templateFile, int administratorId, PortalTemplateModuleAction mergeTabs, bool isNewPortal) + [DnnDeprecated(7, 3, 0, "Use one of the alternate overloads", RemovalVersion = 10)] + public partial void ParseTemplate(int portalId, string templatePath, string templateFile, int administratorId, PortalTemplateModuleAction mergeTabs, bool isNewPortal) { var importer = new PortalTemplateImporter(templatePath, templateFile); importer.ParseTemplate(portalId, administratorId, mergeTabs.ToNewEnum(), isNewPortal); } [EditorBrowsable(EditorBrowsableState.Never)] - [Obsolete("Deprecated in DotNetNuke 7.3.0. Use one of the other overloads. Scheduled removal in v10.0.0.")] - public void ParseTemplate(int portalId, string templatePath, string templateFile, int administratorId, PortalTemplateModuleAction mergeTabs, bool isNewPortal, out LocaleCollection localeCollection) + [DnnDeprecated(7, 3, 0, "Use one of the other overloads", RemovalVersion = 10)] + public partial void ParseTemplate(int portalId, string templatePath, string templateFile, int administratorId, PortalTemplateModuleAction mergeTabs, bool isNewPortal, out LocaleCollection localeCollection) { var importer = new PortalTemplateImporter(templatePath, templateFile); importer.ParseTemplateInternal(portalId, administratorId, mergeTabs.ToNewEnum(), isNewPortal, out localeCollection); } [EditorBrowsable(EditorBrowsableState.Never)] - [Obsolete("Deprecated in DotNetNuke 7.3. Replaced by UpdatePortalExpiry(int, string). Scheduled removal in v10.0.0.")] - public void UpdatePortalExpiry(int portalId) + [DnnDeprecated(7, 3, 0, "Replaced by UpdatePortalExpiry(int, string)", RemovalVersion = 10)] + public partial void UpdatePortalExpiry(int portalId) { this.UpdatePortalExpiry(portalId, GetActivePortalLanguage(portalId)); } [EditorBrowsable(EditorBrowsableState.Never)] - [Obsolete("Deprecated in DotNetNuke 7.3.0. Use one of the alternate overloads. Scheduled removal in v10.0.0.")] - public void UpdatePortalInfo(PortalInfo portal, bool clearCache) + [DnnDeprecated(7, 3, 0, "Use one of the alternate overloads", RemovalVersion = 10)] + public partial void UpdatePortalInfo(PortalInfo portal, bool clearCache) { this.UpdatePortalInternal(portal, clearCache); } diff --git a/DNN Platform/Library/Obsolete/PortalSettings.cs b/DNN Platform/Library/Obsolete/PortalSettings.cs index 45b2f8f75ec..6bc79d6d048 100644 --- a/DNN Platform/Library/Obsolete/PortalSettings.cs +++ b/DNN Platform/Library/Obsolete/PortalSettings.cs @@ -1,18 +1,19 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information -namespace DotNetNuke.Entities.Portals -{ - using System; - using System.ComponentModel; +namespace DotNetNuke.Entities.Portals +{ + using System.ComponentModel; - public partial class PortalSettings - { - [Obsolete("Deprecated in DNN 7.4. Replaced by PortalSettingsController.Instance().GetPortalAliasMappingMode. Scheduled removal in v10.0.0.")] - [EditorBrowsable(EditorBrowsableState.Never)] - public static PortalAliasMapping GetPortalAliasMappingMode(int portalId) - { - return PortalSettingsController.Instance().GetPortalAliasMappingMode(portalId); - } - } -} + using DotNetNuke.Internal.SourceGenerators; + + public partial class PortalSettings + { + [DnnDeprecated(7, 4, 0, "Replaced by PortalSettingsController.Instance().GetPortalAliasMappingMode", RemovalVersion = 10)] + [EditorBrowsable(EditorBrowsableState.Never)] + public static partial PortalAliasMapping GetPortalAliasMappingMode(int portalId) + { + return PortalSettingsController.Instance().GetPortalAliasMappingMode(portalId); + } + } +} diff --git a/DNN Platform/Library/Obsolete/PortalTemplateIOImpl.cs b/DNN Platform/Library/Obsolete/PortalTemplateIOImpl.cs index 7dba607de22..4e4421e97ba 100644 --- a/DNN Platform/Library/Obsolete/PortalTemplateIOImpl.cs +++ b/DNN Platform/Library/Obsolete/PortalTemplateIOImpl.cs @@ -4,7 +4,6 @@ namespace DotNetNuke.Entities.Portals.Internal { - using System; using System.Collections.Generic; using System.ComponentModel; using System.IO; @@ -12,10 +11,11 @@ namespace DotNetNuke.Entities.Portals.Internal using System.Xml; using DotNetNuke.Common; + using DotNetNuke.Internal.SourceGenerators; [EditorBrowsable(EditorBrowsableState.Never)] - [Obsolete("Deprecated in DotNetNuke 7.3.0. Use PortalTemplateIO. Scheduled removal in v10.0.0.")] - public class PortalTemplateIOImpl : IPortalTemplateIO + [DnnDeprecated(7, 3, 0, "Use PortalTemplateIO", RemovalVersion = 10)] + public partial class PortalTemplateIOImpl : IPortalTemplateIO { /// public IEnumerable EnumerateTemplates() diff --git a/DNN Platform/Library/Obsolete/RoleController.cs b/DNN Platform/Library/Obsolete/RoleController.cs index 696407200fc..992f46b46b1 100644 --- a/DNN Platform/Library/Obsolete/RoleController.cs +++ b/DNN Platform/Library/Obsolete/RoleController.cs @@ -2,102 +2,103 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information -namespace DotNetNuke.Security.Roles -{ - using System; - using System.Collections; - using System.ComponentModel; - using System.Linq; +namespace DotNetNuke.Security.Roles +{ + using System; + using System.Collections; + using System.ComponentModel; + using System.Linq; - using DotNetNuke.Common.Utilities; - using DotNetNuke.Entities.Portals; - using DotNetNuke.Entities.Users; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Users; + using DotNetNuke.Internal.SourceGenerators; - /// The RoleController class provides Business Layer methods for Roles. - public partial class RoleController - { - [EditorBrowsable(EditorBrowsableState.Never)] - [Obsolete("Deprecated in DotNetNuke 7.0. This function has been replaced by AddUserRole with additional params. Scheduled removal in v10.0.0.")] - public static void AddUserRole(UserInfo user, RoleInfo role, PortalSettings portalSettings, DateTime effectiveDate, DateTime expiryDate, int userId, bool notifyUser) - { - AddUserRole(user, role, portalSettings, RoleStatus.Approved, effectiveDate, expiryDate, notifyUser, false); - } - - [EditorBrowsable(EditorBrowsableState.Never)] - [Obsolete("Deprecated in DotNetNuke 7.3. This function has been replaced by overload with extra parameters. Scheduled removal in v10.0.0.")] - public void AddUserRole(int portalId, int userId, int roleId, DateTime expiryDate) - { - this.AddUserRole(portalId, userId, roleId, RoleStatus.Approved, false, Null.NullDate, expiryDate); - } - - public void AddUserRole(int portalId, int userId, int roleId, DateTime effectiveDate, DateTime expiryDate) - { - this.AddUserRole(portalId, userId, roleId, RoleStatus.Approved, false, effectiveDate, expiryDate); - } - - [EditorBrowsable(EditorBrowsableState.Never)] - [Obsolete("Deprecated in DotNetNuke 7.3. This function has been replaced by DeleteRole(role). Scheduled removal in v10.0.0.")] - public void DeleteRole(int roleId, int portalId) - { - RoleInfo role = this.GetRole(portalId, r => r.RoleID == roleId); - if (role != null) - { - this.DeleteRole(role); - } - } - - [EditorBrowsable(EditorBrowsableState.Never)] - [Obsolete("Deprecated in DotNetNuke 7.3. This function has been replaced by GetRoles(PortalId, predicate). Scheduled removal in v10.0.0.")] - public ArrayList GetPortalRoles(int portalId) - { - return new ArrayList(Instance.GetRoles(portalId, r => r.SecurityMode != SecurityMode.SocialGroup && r.Status == RoleStatus.Approved).ToArray()); - } - - [EditorBrowsable(EditorBrowsableState.Never)] - [Obsolete("Deprecated in DotNetNuke 7.3. This method has been replacd by GetRoleById. Scheduled removal in v10.0.0.")] - public RoleInfo GetRole(int roleId, int portalId) - { - return this.GetRoleById(portalId, roleId); - } - - [EditorBrowsable(EditorBrowsableState.Never)] - [Obsolete("Deprecated in DotNetNuke 7.3. This function has been replaced by GetRoles(PortalId, predicate). Scheduled removal in v10.0.0.")] - public ArrayList GetRoles() - { - return new ArrayList(Instance.GetRoles(Null.NullInteger, r => r.SecurityMode != SecurityMode.SocialGroup && r.Status == RoleStatus.Approved).ToArray()); - } - - public ArrayList GetRolesByGroup(int portalId, int roleGroupId) - { - return new ArrayList(Instance.GetRoles(portalId, r => r.RoleGroupID == roleGroupId && r.SecurityMode != SecurityMode.SocialGroup && r.Status == RoleStatus.Approved).ToArray()); - } - - [EditorBrowsable(EditorBrowsableState.Never)] - [Obsolete("Deprecated in DotNetNuke 7.3. This method has been replaced by RoleController.Instance.GetUsersByRole(portalId, roleName). Scheduled removal in v10.0.0.")] - public ArrayList GetUsersByRoleName(int portalId, string roleName) - { - return new ArrayList(Instance.GetUsersByRole(portalId, roleName).ToList()); - } - - [EditorBrowsable(EditorBrowsableState.Never)] - [Obsolete("Deprecated in DotNetNuke 7.3. This function has been replaced by RoleController.Instance.UpdateRole(role). Scheduled removal in v10.0.0.")] - public void UpdateRole(RoleInfo role) - { - Instance.UpdateRole(role); - } - - [EditorBrowsable(EditorBrowsableState.Never)] - [Obsolete("Deprecated in DotNetNuke 7.3. This function has been replaced by overload with extra parameters. Scheduled removal in v10.0.0.")] - public void UpdateUserRole(int portalId, int userId, int roleId) - { - this.UpdateUserRole(portalId, userId, roleId, RoleStatus.Approved, false, false); - } - - [EditorBrowsable(EditorBrowsableState.Never)] - [Obsolete("Deprecated in DotNetNuke 7.3. This function has been replaced by overload with extra parameters. Scheduled removal in v10.0.0.")] - public void UpdateUserRole(int portalId, int userId, int roleId, bool cancel) - { - this.UpdateUserRole(portalId, userId, roleId, RoleStatus.Approved, false, cancel); - } - } -} + /// The RoleController class provides Business Layer methods for Roles. + public partial class RoleController + { + [EditorBrowsable(EditorBrowsableState.Never)] + [DnnDeprecated(7, 0, 0, "This function has been replaced by AddUserRole with additional params", RemovalVersion = 10)] + public static partial void AddUserRole(UserInfo user, RoleInfo role, PortalSettings portalSettings, DateTime effectiveDate, DateTime expiryDate, int userId, bool notifyUser) + { + AddUserRole(user, role, portalSettings, RoleStatus.Approved, effectiveDate, expiryDate, notifyUser, false); + } + + [EditorBrowsable(EditorBrowsableState.Never)] + [DnnDeprecated(7, 3, 0, "This function has been replaced by overload with extra parameters", RemovalVersion = 10)] + public partial void AddUserRole(int portalId, int userId, int roleId, DateTime expiryDate) + { + this.AddUserRole(portalId, userId, roleId, RoleStatus.Approved, false, Null.NullDate, expiryDate); + } + + public void AddUserRole(int portalId, int userId, int roleId, DateTime effectiveDate, DateTime expiryDate) + { + this.AddUserRole(portalId, userId, roleId, RoleStatus.Approved, false, effectiveDate, expiryDate); + } + + [EditorBrowsable(EditorBrowsableState.Never)] + [DnnDeprecated(7, 3, 0, "This function has been replaced by DeleteRole(role)", RemovalVersion = 10)] + public partial void DeleteRole(int roleId, int portalId) + { + RoleInfo role = this.GetRole(portalId, r => r.RoleID == roleId); + if (role != null) + { + this.DeleteRole(role); + } + } + + [EditorBrowsable(EditorBrowsableState.Never)] + [DnnDeprecated(7, 3, 0, "This function has been replaced by GetRoles(PortalId, predicate)", RemovalVersion = 10)] + public partial ArrayList GetPortalRoles(int portalId) + { + return new ArrayList(Instance.GetRoles(portalId, r => r.SecurityMode != SecurityMode.SocialGroup && r.Status == RoleStatus.Approved).ToArray()); + } + + [EditorBrowsable(EditorBrowsableState.Never)] + [DnnDeprecated(7, 3, 0, "This method has been replaced by GetRoleById", RemovalVersion = 10)] + public partial RoleInfo GetRole(int roleId, int portalId) + { + return this.GetRoleById(portalId, roleId); + } + + [EditorBrowsable(EditorBrowsableState.Never)] + [DnnDeprecated(7, 3, 0, "This function has been replaced by GetRoles(PortalId, predicate)", RemovalVersion = 10)] + public partial ArrayList GetRoles() + { + return new ArrayList(Instance.GetRoles(Null.NullInteger, r => r.SecurityMode != SecurityMode.SocialGroup && r.Status == RoleStatus.Approved).ToArray()); + } + + public ArrayList GetRolesByGroup(int portalId, int roleGroupId) + { + return new ArrayList(Instance.GetRoles(portalId, r => r.RoleGroupID == roleGroupId && r.SecurityMode != SecurityMode.SocialGroup && r.Status == RoleStatus.Approved).ToArray()); + } + + [EditorBrowsable(EditorBrowsableState.Never)] + [DnnDeprecated(7, 3, 0, "This method has been replaced by RoleController.Instance.GetUsersByRole(portalId, roleName)", RemovalVersion = 10)] + public partial ArrayList GetUsersByRoleName(int portalId, string roleName) + { + return new ArrayList(Instance.GetUsersByRole(portalId, roleName).ToList()); + } + + [EditorBrowsable(EditorBrowsableState.Never)] + [DnnDeprecated(7, 3, 0, "This function has been replaced by RoleController.Instance.UpdateRole(role)", RemovalVersion = 10)] + public partial void UpdateRole(RoleInfo role) + { + Instance.UpdateRole(role); + } + + [EditorBrowsable(EditorBrowsableState.Never)] + [DnnDeprecated(7, 3, 0, "This function has been replaced by overload with extra parameters", RemovalVersion = 10)] + public partial void UpdateUserRole(int portalId, int userId, int roleId) + { + this.UpdateUserRole(portalId, userId, roleId, RoleStatus.Approved, false, false); + } + + [EditorBrowsable(EditorBrowsableState.Never)] + [DnnDeprecated(7, 3, 0, "This function has been replaced by overload with extra parameters", RemovalVersion = 10)] + public partial void UpdateUserRole(int portalId, int userId, int roleId, bool cancel) + { + this.UpdateUserRole(portalId, userId, roleId, RoleStatus.Approved, false, cancel); + } + } +} diff --git a/DNN Platform/Library/Obsolete/SerializationController.cs b/DNN Platform/Library/Obsolete/SerializationController.cs index 3a005bdb32b..f9d988ab130 100644 --- a/DNN Platform/Library/Obsolete/SerializationController.cs +++ b/DNN Platform/Library/Obsolete/SerializationController.cs @@ -1,35 +1,36 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information -namespace DotNetNuke.Entities.Modules.Settings -{ - using System; - using System.Reflection; - - using DotNetNuke.Abstractions; - using DotNetNuke.Common; - using Microsoft.Extensions.DependencyInjection; - - [Obsolete("Deprecated in 9.8.0. Use Dependency Injection to resolve 'DotNetNuke.Abstractions.ISerializationManager' instead. Scheduled for removal in v11.0.0.")] - public partial class SerializationController - { - private static ISerializationManager SerializationManager => - Globals.DependencyProvider.GetRequiredService(); - - [Obsolete("Deprecated in 9.8.0. Use Dependency Injection to resolve 'DotNetNuke.Abstractions.ISerializationManager' instead. Scheduled for removal in v11.0.0.")] - public static string SerializeProperty(T myObject, PropertyInfo property) => - SerializationManager.SerializeProperty(myObject, property); - - [Obsolete("Deprecated in 9.8.0. Use Dependency Injection to resolve 'DotNetNuke.Abstractions.ISerializationManager' instead. Scheduled for removal in v11.0.0.")] - public static string SerializeProperty(T myObject, PropertyInfo property, string serializer) => - SerializationManager.SerializeProperty(myObject, property, serializer); - - [Obsolete("Deprecated in 9.8.0. Use Dependency Injection to resolve 'DotNetNuke.Abstractions.ISerializationManager' instead. Scheduled for removal in v11.0.0.")] - public static void DeserializeProperty(T myObject, PropertyInfo property, string propertyValue) - where T : class, new() => SerializationManager.DeserializeProperty(myObject, property, propertyValue); - - [Obsolete("Deprecated in 9.8.0. Use Dependency Injection to resolve 'DotNetNuke.Abstractions.ISerializationManager' instead. Scheduled for removal in v11.0.0.")] - public static void DeserializeProperty(T myObject, PropertyInfo property, string propertyValue, string serializer) - where T : class, new() => SerializationManager.DeserializeProperty(myObject, property, propertyValue, serializer); - } -} +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information +namespace DotNetNuke.Entities.Modules.Settings +{ + using System.Reflection; + + using DotNetNuke.Abstractions; + using DotNetNuke.Common; + using DotNetNuke.Internal.SourceGenerators; + + using Microsoft.Extensions.DependencyInjection; + + [DnnDeprecated(9, 8, 0, "Use Dependency Injection to resolve 'DotNetNuke.Abstractions.ISerializationManager' instead")] + public partial class SerializationController + { + private static ISerializationManager SerializationManager => + Globals.DependencyProvider.GetRequiredService(); + + [DnnDeprecated(9, 8, 0, "Use Dependency Injection to resolve 'DotNetNuke.Abstractions.ISerializationManager' instead")] + public static partial string SerializeProperty(T myObject, PropertyInfo property) => + SerializationManager.SerializeProperty(myObject, property); + + [DnnDeprecated(9, 8, 0, "Use Dependency Injection to resolve 'DotNetNuke.Abstractions.ISerializationManager' instead")] + public static partial string SerializeProperty(T myObject, PropertyInfo property, string serializer) => + SerializationManager.SerializeProperty(myObject, property, serializer); + + [DnnDeprecated(9, 8, 0, "Use Dependency Injection to resolve 'DotNetNuke.Abstractions.ISerializationManager' instead")] + public static partial void DeserializeProperty(T myObject, PropertyInfo property, string propertyValue) + where T : class, new() => SerializationManager.DeserializeProperty(myObject, property, propertyValue); + + [DnnDeprecated(9, 8, 0, "Use Dependency Injection to resolve 'DotNetNuke.Abstractions.ISerializationManager' instead")] + public static partial void DeserializeProperty(T myObject, PropertyInfo property, string propertyValue, string serializer) + where T : class, new() => SerializationManager.DeserializeProperty(myObject, property, propertyValue, serializer); + } +} diff --git a/DNN Platform/Library/Obsolete/TabController.cs b/DNN Platform/Library/Obsolete/TabController.cs index 74b911429a9..a4638a52485 100644 --- a/DNN Platform/Library/Obsolete/TabController.cs +++ b/DNN Platform/Library/Obsolete/TabController.cs @@ -1,129 +1,130 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information -namespace DotNetNuke.Entities.Tabs -{ - using System; - using System.Collections; - using System.Collections.Generic; - using System.ComponentModel; - using System.Linq; +namespace DotNetNuke.Entities.Tabs +{ + using System; + using System.Collections; + using System.Collections.Generic; + using System.ComponentModel; + using System.Linq; - using DotNetNuke.Common.Utilities; - using DotNetNuke.Entities.Portals; - using DotNetNuke.Services.Localization; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Internal.SourceGenerators; + using DotNetNuke.Services.Localization; - /// TabController provides all operation to tabinfo. - /// - /// Tab is equal to page in DotNetNuke. - /// Tabs will be a sitemap for a poatal, and every request at first need to check whether there is valid tab information - /// include in the url, if not it will use default tab to display information. - /// - public partial class TabController - { - [EditorBrowsable(EditorBrowsableState.Never)] - [Obsolete("Deprecated in DotNetNuke 7.3. RUse alternate overload. Scheduled removal in v10.0.0.")] - public void CreateLocalizedCopy(List tabs, Locale locale) - { - foreach (TabInfo t in tabs) - { - this.CreateLocalizedCopy(t, locale, true); - } - } - - [EditorBrowsable(EditorBrowsableState.Never)] - [Obsolete("Deprecated in DotNetNuke 7.3. RUse alternate overload. Scheduled removal in v10.0.0.")] - public void CreateLocalizedCopy(TabInfo originalTab, Locale locale) - { - this.CreateLocalizedCopy(originalTab, locale, true); - } - - [EditorBrowsable(EditorBrowsableState.Never)] - [Obsolete("Deprecated in DNN 7.3. Method is not scalable. Use GetTabsByPortal. Scheduled removal in v10.0.0.")] - public ArrayList GetAllTabs() - { - return CBO.FillCollection(this.dataProvider.GetAllTabs(), typeof(TabInfo)); - } - - [EditorBrowsable(EditorBrowsableState.Never)] - [Obsolete("Deprecated in DNN 7.3. Method is not neccessary. Use LINQ and GetPortalTabs(). Scheduled removal in v10.0.0.")] - public List GetCultureTabList(int portalid) - { - return (from kvp in this.GetTabsByPortal(portalid) - where !kvp.Value.TabPath.StartsWith("//Admin") - && kvp.Value.CultureCode == PortalController.Instance.GetCurrentPortalSettings().DefaultLanguage - && !kvp.Value.IsDeleted - select kvp.Value).ToList(); - } - - [EditorBrowsable(EditorBrowsableState.Never)] - [Obsolete("Deprecated in DNN 7.3. Method is not neccessary. Use LINQ and GetPortalTabs(). Scheduled removal in v10.0.0.")] - public List GetDefaultCultureTabList(int portalid) - { - return (from kvp in this.GetTabsByPortal(portalid) - where !kvp.Value.TabPath.StartsWith("//Admin") - && !kvp.Value.IsDeleted - select kvp.Value).ToList(); - } - - [EditorBrowsable(EditorBrowsableState.Never)] - [Obsolete("This method is obsolete. It has been replaced by GetTab(ByVal TabId As Integer, ByVal PortalId As Integer, ByVal ignoreCache As Boolean) . Scheduled removal in v10.0.0.")] - public TabInfo GetTab(int tabId) - { - return this.GetTab(tabId, GetPortalId(tabId, Null.NullInteger), false); - } - - [EditorBrowsable(EditorBrowsableState.Never)] - [Obsolete("Deprecated in DNN 7.3. Use LINQ queries on tab collections thata re cached. Scheduled removal in v10.0.0.")] - public TabInfo GetTabByUniqueID(Guid uniqueID) - { - return CBO.FillObject(this.dataProvider.GetTabByUniqueID(uniqueID)); - } - - [EditorBrowsable(EditorBrowsableState.Never)] - [Obsolete("Deprecated in DNN 7.3. Use GetTabsByPortal(portalId).Count. Scheduled removal in v10.0.0.")] - public int GetTabCount(int portalId) - { - return this.GetTabsByPortal(portalId).Count; - } - - [EditorBrowsable(EditorBrowsableState.Never)] - [Obsolete("This method is obsolete. It has been replaced by GetTabsByParent(ByVal ParentId As Integer, ByVal PortalId As Integer) . Scheduled removal in v10.0.0.")] - public ArrayList GetTabsByParentId(int parentId) - { - return new ArrayList(GetTabsByParent(parentId, GetPortalId(parentId, Null.NullInteger))); - } - - [EditorBrowsable(EditorBrowsableState.Never)] - [Obsolete("Deprecated in DNN 7.3. Use one of the alternate MoveTabxxx methods). Scheduled removal in v10.0.0.")] - public void MoveTab(TabInfo tab, TabMoveType type) - { - // Get the List of tabs with the same parent - IOrderedEnumerable siblingTabs = this.GetSiblingTabs(tab).OrderBy(t => t.TabOrder); - int tabIndex = GetIndexOfTab(tab, siblingTabs); - switch (type) - { - case TabMoveType.Top: - this.MoveTabBefore(tab, siblingTabs.First().TabID); - break; - case TabMoveType.Bottom: - this.MoveTabAfter(tab, siblingTabs.Last().TabID); - break; - case TabMoveType.Up: - this.MoveTabBefore(tab, siblingTabs.ElementAt(tabIndex - 1).TabID); - break; - case TabMoveType.Down: - this.MoveTabAfter(tab, siblingTabs.ElementAt(tabIndex + 1).TabID); - break; - case TabMoveType.Promote: - this.MoveTabAfter(tab, tab.ParentId); - break; - case TabMoveType.Demote: - this.MoveTabToParent(tab, siblingTabs.ElementAt(tabIndex - 1).TabID); - break; - } - - this.ClearCache(tab.PortalID); - } - } -} + /// TabController provides all operation to tabinfo. + /// + /// Tab is equal to page in DotNetNuke. + /// Tabs will be a sitemap for a poatal, and every request at first need to check whether there is valid tab information + /// include in the url, if not it will use default tab to display information. + /// + public partial class TabController + { + [EditorBrowsable(EditorBrowsableState.Never)] + [DnnDeprecated(7, 3, 0, "Use alternate overload", RemovalVersion = 10)] + public partial void CreateLocalizedCopy(List tabs, Locale locale) + { + foreach (TabInfo t in tabs) + { + this.CreateLocalizedCopy(t, locale, true); + } + } + + [EditorBrowsable(EditorBrowsableState.Never)] + [DnnDeprecated(7, 3, 0, "Use alternate overload", RemovalVersion = 10)] + public partial void CreateLocalizedCopy(TabInfo originalTab, Locale locale) + { + this.CreateLocalizedCopy(originalTab, locale, true); + } + + [EditorBrowsable(EditorBrowsableState.Never)] + [DnnDeprecated(7, 3, 0, "Method is not scalable. Use GetTabsByPortal", RemovalVersion = 10)] + public partial ArrayList GetAllTabs() + { + return CBO.FillCollection(this.dataProvider.GetAllTabs(), typeof(TabInfo)); + } + + [EditorBrowsable(EditorBrowsableState.Never)] + [DnnDeprecated(7, 3, 0, "Method is not necessary. Use LINQ and GetPortalTabs()", RemovalVersion = 10)] + public partial List GetCultureTabList(int portalid) + { + return (from kvp in this.GetTabsByPortal(portalid) + where !kvp.Value.TabPath.StartsWith("//Admin") + && kvp.Value.CultureCode == PortalController.Instance.GetCurrentPortalSettings().DefaultLanguage + && !kvp.Value.IsDeleted + select kvp.Value).ToList(); + } + + [EditorBrowsable(EditorBrowsableState.Never)] + [DnnDeprecated(7, 3, 0, "Method is not necessary. Use LINQ and GetPortalTabs()", RemovalVersion = 10)] + public partial List GetDefaultCultureTabList(int portalid) + { + return (from kvp in this.GetTabsByPortal(portalid) + where !kvp.Value.TabPath.StartsWith("//Admin") + && !kvp.Value.IsDeleted + select kvp.Value).ToList(); + } + + [EditorBrowsable(EditorBrowsableState.Never)] + [DnnDeprecated(7, 0, 0, "Replaced by GetTab(int tabId, int portalId, bool ignoreCache)", RemovalVersion = 10)] + public partial TabInfo GetTab(int tabId) + { + return this.GetTab(tabId, GetPortalId(tabId, Null.NullInteger), false); + } + + [EditorBrowsable(EditorBrowsableState.Never)] + [DnnDeprecated(7, 3, 0, "Use LINQ queries on tab collections that are cached", RemovalVersion = 10)] + public partial TabInfo GetTabByUniqueID(Guid uniqueID) + { + return CBO.FillObject(this.dataProvider.GetTabByUniqueID(uniqueID)); + } + + [EditorBrowsable(EditorBrowsableState.Never)] + [DnnDeprecated(7, 3, 0, "Use GetTabsByPortal(portalId).Count", RemovalVersion = 10)] + public partial int GetTabCount(int portalId) + { + return this.GetTabsByPortal(portalId).Count; + } + + [EditorBrowsable(EditorBrowsableState.Never)] + [DnnDeprecated(7, 0, 0, "Replaced by GetTabsByParent(int parentId, int portalId)", RemovalVersion = 10)] + public partial ArrayList GetTabsByParentId(int parentId) + { + return new ArrayList(GetTabsByParent(parentId, GetPortalId(parentId, Null.NullInteger))); + } + + [EditorBrowsable(EditorBrowsableState.Never)] + [DnnDeprecated(7, 3, 0, "Use one of the alternate MoveTabxxx methods", RemovalVersion = 10)] + public partial void MoveTab(TabInfo tab, TabMoveType type) + { + // Get the List of tabs with the same parent + IOrderedEnumerable siblingTabs = this.GetSiblingTabs(tab).OrderBy(t => t.TabOrder); + int tabIndex = GetIndexOfTab(tab, siblingTabs); + switch (type) + { + case TabMoveType.Top: + this.MoveTabBefore(tab, siblingTabs.First().TabID); + break; + case TabMoveType.Bottom: + this.MoveTabAfter(tab, siblingTabs.Last().TabID); + break; + case TabMoveType.Up: + this.MoveTabBefore(tab, siblingTabs.ElementAt(tabIndex - 1).TabID); + break; + case TabMoveType.Down: + this.MoveTabAfter(tab, siblingTabs.ElementAt(tabIndex + 1).TabID); + break; + case TabMoveType.Promote: + this.MoveTabAfter(tab, tab.ParentId); + break; + case TabMoveType.Demote: + this.MoveTabToParent(tab, siblingTabs.ElementAt(tabIndex - 1).TabID); + break; + } + + this.ClearCache(tab.PortalID); + } + } +} diff --git a/DNN Platform/Library/Obsolete/TestableModuleController.cs b/DNN Platform/Library/Obsolete/TestableModuleController.cs index f7d24a4b712..80e0be26b06 100644 --- a/DNN Platform/Library/Obsolete/TestableModuleController.cs +++ b/DNN Platform/Library/Obsolete/TestableModuleController.cs @@ -1,39 +1,40 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information -namespace DotNetNuke.Entities.Modules.Internal -{ - using System; - using System.ComponentModel; +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information +namespace DotNetNuke.Entities.Modules.Internal +{ + using System; + using System.ComponentModel; - using DotNetNuke.Framework; + using DotNetNuke.Framework; + using DotNetNuke.Internal.SourceGenerators; - [EditorBrowsable(EditorBrowsableState.Never)] - [Obsolete("This class has been obsoleted in 7.3.0 - please use ModuleController instead. Scheduled removal in v10.0.0.")] - public class TestableModuleController : ServiceLocator, IModuleController + [EditorBrowsable(EditorBrowsableState.Never)] + [DnnDeprecated(7, 3, 0, "Please use ModuleController instead", RemovalVersion = 10)] + public partial class TestableModuleController : ServiceLocator, IModuleController { /// - public ModuleInfo GetModule(int moduleId, int tabId) - { - return ModuleController.Instance.GetModule(moduleId, tabId, false); + public ModuleInfo GetModule(int moduleId, int tabId) + { + return ModuleController.Instance.GetModule(moduleId, tabId, false); } /// - public void UpdateModuleSetting(int moduleId, string settingName, string settingValue) - { - ModuleController.Instance.UpdateModuleSetting(moduleId, settingName, settingValue); + public void UpdateModuleSetting(int moduleId, string settingName, string settingValue) + { + ModuleController.Instance.UpdateModuleSetting(moduleId, settingName, settingValue); } /// - public void UpdateTabModuleSetting(int tabModuleId, string settingName, string settingValue) - { - ModuleController.Instance.UpdateTabModuleSetting(tabModuleId, settingName, settingValue); + public void UpdateTabModuleSetting(int tabModuleId, string settingName, string settingValue) + { + ModuleController.Instance.UpdateTabModuleSetting(tabModuleId, settingName, settingValue); } /// - protected override Func GetFactory() - { - return () => new TestableModuleController(); - } - } -} + protected override Func GetFactory() + { + return () => new TestableModuleController(); + } + } +} diff --git a/DNN Platform/Library/Obsolete/TestablePortalAliasController.cs b/DNN Platform/Library/Obsolete/TestablePortalAliasController.cs index d5ee8b5ec97..5419e42436d 100644 --- a/DNN Platform/Library/Obsolete/TestablePortalAliasController.cs +++ b/DNN Platform/Library/Obsolete/TestablePortalAliasController.cs @@ -2,59 +2,60 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information -namespace DotNetNuke.Entities.Portals.Internal -{ - using System; - using System.Collections.Generic; - using System.ComponentModel; - - using DotNetNuke.Framework; - - [EditorBrowsable(EditorBrowsableState.Never)] - [Obsolete("This class has been obsoleted in 7.3.0 - please use PortalAliasController instead. Scheduled removal in v10.0.0.")] - public class TestablePortalAliasController : ServiceLocator, IPortalAliasController +namespace DotNetNuke.Entities.Portals.Internal +{ + using System; + using System.Collections.Generic; + using System.ComponentModel; + + using DotNetNuke.Framework; + using DotNetNuke.Internal.SourceGenerators; + + [EditorBrowsable(EditorBrowsableState.Never)] + [DnnDeprecated(7, 3, 0, "Please use PortalAliasController instead", RemovalVersion = 10)] + public partial class TestablePortalAliasController : ServiceLocator, IPortalAliasController { /// - public int AddPortalAlias(PortalAliasInfo portalAlias) - { - return PortalAliasController.Instance.AddPortalAlias(portalAlias); + public int AddPortalAlias(PortalAliasInfo portalAlias) + { + return PortalAliasController.Instance.AddPortalAlias(portalAlias); } /// - public void DeletePortalAlias(PortalAliasInfo portalAlias) - { - PortalAliasController.Instance.DeletePortalAlias(portalAlias); + public void DeletePortalAlias(PortalAliasInfo portalAlias) + { + PortalAliasController.Instance.DeletePortalAlias(portalAlias); } /// - public PortalAliasInfo GetPortalAlias(string alias) - { - return PortalAliasController.Instance.GetPortalAlias(alias); + public PortalAliasInfo GetPortalAlias(string alias) + { + return PortalAliasController.Instance.GetPortalAlias(alias); } /// - public IEnumerable GetPortalAliasesByPortalId(int portalId) - { - return PortalAliasController.Instance.GetPortalAliasesByPortalId(portalId); + public IEnumerable GetPortalAliasesByPortalId(int portalId) + { + return PortalAliasController.Instance.GetPortalAliasesByPortalId(portalId); } /// - public IDictionary GetPortalAliases() - { - var aliasController = new PortalAliasController(); - return aliasController.GetPortalAliasesInternal(); + public IDictionary GetPortalAliases() + { + var aliasController = new PortalAliasController(); + return aliasController.GetPortalAliasesInternal(); } /// - public void UpdatePortalAlias(PortalAliasInfo portalAlias) - { - PortalAliasController.Instance.UpdatePortalAlias(portalAlias); + public void UpdatePortalAlias(PortalAliasInfo portalAlias) + { + PortalAliasController.Instance.UpdatePortalAlias(portalAlias); } /// - protected override Func GetFactory() - { - return () => new TestablePortalAliasController(); - } - } -} + protected override Func GetFactory() + { + return () => new TestablePortalAliasController(); + } + } +} diff --git a/DNN Platform/Library/Obsolete/TestablePortalController.cs b/DNN Platform/Library/Obsolete/TestablePortalController.cs index 17d3fc08210..97d8e2c1a64 100644 --- a/DNN Platform/Library/Obsolete/TestablePortalController.cs +++ b/DNN Platform/Library/Obsolete/TestablePortalController.cs @@ -2,21 +2,22 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information -namespace DotNetNuke.Entities.Portals.Internal -{ - using System; - using System.ComponentModel; +namespace DotNetNuke.Entities.Portals.Internal +{ + using System; + using System.ComponentModel; - using DotNetNuke.Framework; + using DotNetNuke.Framework; + using DotNetNuke.Internal.SourceGenerators; - [EditorBrowsable(EditorBrowsableState.Never)] - [Obsolete("This class has been obsoleted in 7.3.0 - please use PortalController instead. Scheduled removal in v10.0.0.")] - public class TestablePortalController : ServiceLocator + [EditorBrowsable(EditorBrowsableState.Never)] + [DnnDeprecated(7, 3, 0, "Please use PortalController instead", RemovalVersion = 10)] + public partial class TestablePortalController : ServiceLocator { /// - protected override Func GetFactory() - { - return () => new PortalController(); - } - } -} + protected override Func GetFactory() + { + return () => new PortalController(); + } + } +} diff --git a/DNN Platform/Library/Obsolete/TestablePortalSettings.cs b/DNN Platform/Library/Obsolete/TestablePortalSettings.cs index d2a77c70f4a..c76b0f04459 100644 --- a/DNN Platform/Library/Obsolete/TestablePortalSettings.cs +++ b/DNN Platform/Library/Obsolete/TestablePortalSettings.cs @@ -2,22 +2,22 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information -namespace DotNetNuke.Entities.Portals.Internal -{ - using System; - using System.ComponentModel; +namespace DotNetNuke.Entities.Portals.Internal +{ + using System.ComponentModel; - using DotNetNuke.ComponentModel; - using DotNetNuke.Entities.Portals; + using DotNetNuke.ComponentModel; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Internal.SourceGenerators; - [EditorBrowsable(EditorBrowsableState.Never)] - [Obsolete("Deprecated in DotNetNuke 7.3.0. Use PortalController.Instance.GetCurrentPortalSettings to get a mockable PortalSettings. Scheduled removal in v10.0.0.")] - public class TestablePortalSettings : ComponentBase, IPortalSettings + [EditorBrowsable(EditorBrowsableState.Never)] + [DnnDeprecated(7, 3, 0, "Use PortalController.Instance.GetCurrentPortalSettings to get a mockable PortalSettings", RemovalVersion = 10)] + public partial class TestablePortalSettings : ComponentBase, IPortalSettings { /// - public string AdministratorRoleName - { - get { return PortalSettings.Current.AdministratorRoleName; } - } - } -} + public string AdministratorRoleName + { + get { return PortalSettings.Current.AdministratorRoleName; } + } + } +} diff --git a/DNN Platform/Library/Obsolete/TestableRoleController.cs b/DNN Platform/Library/Obsolete/TestableRoleController.cs index 6b725527ee1..ac4fa5bb459 100644 --- a/DNN Platform/Library/Obsolete/TestableRoleController.cs +++ b/DNN Platform/Library/Obsolete/TestableRoleController.cs @@ -2,94 +2,95 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information -namespace DotNetNuke.Security.Roles.Internal -{ - using System; - using System.Collections.Generic; - using System.ComponentModel; +namespace DotNetNuke.Security.Roles.Internal +{ + using System; + using System.Collections.Generic; + using System.ComponentModel; - using DotNetNuke.Framework; + using DotNetNuke.Framework; + using DotNetNuke.Internal.SourceGenerators; - [EditorBrowsable(EditorBrowsableState.Never)] - [Obsolete("This class has been obsoleted in 7.3.0 - please use RoleController instead. Scheduled removal in v10.0.0.")] - public class TestableRoleController : ServiceLocator, IRoleController + [EditorBrowsable(EditorBrowsableState.Never)] + [DnnDeprecated(7, 3, 0, "Please use RoleController instead", RemovalVersion = 10)] + public partial class TestableRoleController : ServiceLocator, IRoleController { /// - public int AddRole(RoleInfo role) - { - return RoleController.Instance.AddRole(role); + public int AddRole(RoleInfo role) + { + return RoleController.Instance.AddRole(role); } /// - public int AddRole(RoleInfo role, bool addToExistUsers) - { - return RoleController.Instance.AddRole(role, addToExistUsers); + public int AddRole(RoleInfo role, bool addToExistUsers) + { + return RoleController.Instance.AddRole(role, addToExistUsers); } /// - public void DeleteRole(RoleInfo role) - { - RoleController.Instance.DeleteRole(role); + public void DeleteRole(RoleInfo role) + { + RoleController.Instance.DeleteRole(role); } /// - public RoleInfo GetRole(int portalId, Func predicate) - { - return RoleController.Instance.GetRole(portalId, predicate); + public RoleInfo GetRole(int portalId, Func predicate) + { + return RoleController.Instance.GetRole(portalId, predicate); } /// - public IList GetRoles(int portalId) - { - return RoleController.Instance.GetRoles(portalId); + public IList GetRoles(int portalId) + { + return RoleController.Instance.GetRoles(portalId); } /// - public IList GetRolesBasicSearch(int portalID, int pageSize, string filterBy) - { - return RoleController.Instance.GetRolesBasicSearch(portalID, pageSize, filterBy); + public IList GetRolesBasicSearch(int portalID, int pageSize, string filterBy) + { + return RoleController.Instance.GetRolesBasicSearch(portalID, pageSize, filterBy); } /// - public IList GetRoles(int portalId, Func predicate) - { - return RoleController.Instance.GetRoles(portalId, predicate); + public IList GetRoles(int portalId, Func predicate) + { + return RoleController.Instance.GetRoles(portalId, predicate); } /// - public IDictionary GetRoleSettings(int roleId) - { - return RoleController.Instance.GetRoleSettings(roleId); + public IDictionary GetRoleSettings(int roleId) + { + return RoleController.Instance.GetRoleSettings(roleId); } /// - public void UpdateRole(RoleInfo role) - { - RoleController.Instance.UpdateRole(role); + public void UpdateRole(RoleInfo role) + { + RoleController.Instance.UpdateRole(role); } /// - public void UpdateRole(RoleInfo role, bool addToExistUsers) - { - RoleController.Instance.UpdateRole(role, addToExistUsers); + public void UpdateRole(RoleInfo role, bool addToExistUsers) + { + RoleController.Instance.UpdateRole(role, addToExistUsers); } /// - public void UpdateRoleSettings(RoleInfo role, bool clearCache) - { - RoleController.Instance.UpdateRoleSettings(role, clearCache); + public void UpdateRoleSettings(RoleInfo role, bool clearCache) + { + RoleController.Instance.UpdateRoleSettings(role, clearCache); } /// - public void ClearRoleCache(int portalId) - { - RoleController.Instance.ClearRoleCache(portalId); + public void ClearRoleCache(int portalId) + { + RoleController.Instance.ClearRoleCache(portalId); } /// - protected override Func GetFactory() - { - return () => new TestableRoleController(); - } - } -} + protected override Func GetFactory() + { + return () => new TestableRoleController(); + } + } +} diff --git a/DNN Platform/Library/Obsolete/TestableTabController.cs b/DNN Platform/Library/Obsolete/TestableTabController.cs index aeb667e3c2b..29e189ab60f 100644 --- a/DNN Platform/Library/Obsolete/TestableTabController.cs +++ b/DNN Platform/Library/Obsolete/TestableTabController.cs @@ -2,58 +2,59 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information -namespace DotNetNuke.Entities.Tabs.Internal -{ - using System; - using System.Collections.Generic; - using System.ComponentModel; - - using DotNetNuke.Framework; - - [EditorBrowsable(EditorBrowsableState.Never)] - [Obsolete("This class has been obsoleted in 7.3.0 - please use TabController instead. Scheduled removal in v10.0.0.")] - public class TestableTabController : ServiceLocator, ITabController +namespace DotNetNuke.Entities.Tabs.Internal +{ + using System; + using System.Collections.Generic; + using System.ComponentModel; + + using DotNetNuke.Framework; + using DotNetNuke.Internal.SourceGenerators; + + [EditorBrowsable(EditorBrowsableState.Never)] + [DnnDeprecated(7, 3, 0, "Please use TabController instead", RemovalVersion = 10)] + public partial class TestableTabController : ServiceLocator, ITabController { /// - public void DeleteTabUrl(TabUrlInfo tabUrl, int portalId, bool clearCache) - { - TabController.Instance.DeleteTabUrl(tabUrl, portalId, clearCache); + public void DeleteTabUrl(TabUrlInfo tabUrl, int portalId, bool clearCache) + { + TabController.Instance.DeleteTabUrl(tabUrl, portalId, clearCache); } /// - public TabInfo GetTab(int tabId, int portalId) - { - return TabController.Instance.GetTab(tabId, portalId); + public TabInfo GetTab(int tabId, int portalId) + { + return TabController.Instance.GetTab(tabId, portalId); } /// - public Dictionary GetCustomAliases(int tabId, int portalId) - { - return TabController.Instance.GetCustomAliases(tabId, portalId); + public Dictionary GetCustomAliases(int tabId, int portalId) + { + return TabController.Instance.GetCustomAliases(tabId, portalId); } /// - public List GetAliasSkins(int tabId, int portalId) - { - return TabController.Instance.GetAliasSkins(tabId, portalId); + public List GetAliasSkins(int tabId, int portalId) + { + return TabController.Instance.GetAliasSkins(tabId, portalId); } /// - public List GetTabUrls(int tabId, int portalId) - { - return TabController.Instance.GetTabUrls(tabId, portalId); + public List GetTabUrls(int tabId, int portalId) + { + return TabController.Instance.GetTabUrls(tabId, portalId); } /// - public void SaveTabUrl(TabUrlInfo tabUrl, int portalId, bool clearCache) - { - TabController.Instance.SaveTabUrl(tabUrl, portalId, clearCache); + public void SaveTabUrl(TabUrlInfo tabUrl, int portalId, bool clearCache) + { + TabController.Instance.SaveTabUrl(tabUrl, portalId, clearCache); } /// - protected override Func GetFactory() - { - return () => new TestableTabController(); - } - } -} + protected override Func GetFactory() + { + return () => new TestableTabController(); + } + } +} diff --git a/DNN Platform/Library/Obsolete/TestableUserController.cs b/DNN Platform/Library/Obsolete/TestableUserController.cs index 0fe7c52f872..767bba80683 100644 --- a/DNN Platform/Library/Obsolete/TestableUserController.cs +++ b/DNN Platform/Library/Obsolete/TestableUserController.cs @@ -8,10 +8,11 @@ namespace DotNetNuke.Entities.Users.Internal using System.ComponentModel; using DotNetNuke.Framework; + using DotNetNuke.Internal.SourceGenerators; [EditorBrowsable(EditorBrowsableState.Never)] - [Obsolete("This class has been obsoleted in 7.3.0 - please use UserController instead. Scheduled removal in v10.0.0.")] - public class TestableUserController : ServiceLocator, IUserController + [DnnDeprecated(7, 3, 0, "Please use UserController instead", RemovalVersion = 10)] + public partial class TestableUserController : ServiceLocator, IUserController { /// public UserInfo GetUserByDisplayname(int portalId, string displayName) diff --git a/DNN Platform/Library/Obsolete/UserController.cs b/DNN Platform/Library/Obsolete/UserController.cs index 8c857cc1e01..2de3e07b350 100644 --- a/DNN Platform/Library/Obsolete/UserController.cs +++ b/DNN Platform/Library/Obsolete/UserController.cs @@ -2,138 +2,139 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information -namespace DotNetNuke.Entities.Users -{ - using System; - using System.ComponentModel; - using System.Data; +namespace DotNetNuke.Entities.Users +{ + using System; + using System.ComponentModel; + using System.Data; - using DotNetNuke.Common.Utilities; - using DotNetNuke.Entities.Portals; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Internal.SourceGenerators; - /// The UserController class provides Business Layer methods for Users. - /// - /// DotNetNuke user management is base on asp.net membership provider, but the default implementation of these providers - /// do not satisfy the broad set of use cases which we need to support in DotNetNuke. so The dependency of DotNetNuke on the - /// MemberRole (ASP.NET 2 Membership) components will be abstracted into a DotNetNuke Membership Provider, in order to allow - /// developers complete flexibility in implementing alternate Membership approaches. - /// - /// This will allow for a number of enhancements to be added - /// Removal of dependence on the HttpContext - /// Support for Hashed Passwords - /// Support for Password Question and Answer - /// Enforce Password Complexity - /// Password Aging (Expiry) - /// Force Password Update - /// Enable/Disable Password Retrieval/Reset - /// CAPTCHA Support - /// Redirect after registration/login/logout - /// - /// - /// - public partial class UserController - { - [EditorBrowsable(EditorBrowsableState.Never)] - [Obsolete("Deprecated in DNN 7.2.2. This method has been replaced by UserController.MoveUserToPortal and UserControllar.CopyUserToPortal. Scheduled removal in v10.0.0.")] - public static void CopyUserToPortal(UserInfo user, PortalInfo portal, bool mergeUser, bool deleteUser) - { - if (deleteUser) - { - MoveUserToPortal(user, portal, mergeUser); - } - else - { - CopyUserToPortal(user, portal, mergeUser); - } - } - - [EditorBrowsable(EditorBrowsableState.Never)] - [Obsolete("Deprecated in DNN 7.3. Replaced by UserController.Instance.GetCurrentUserInfo(). Scheduled removal in v10.0.0.")] - public static UserInfo GetCurrentUserInfo() - { - return GetCurrentUserInternal(); - } - - /// - /// overload will validate the token and if valid change the password - /// it does not require an old password as it supports hashed passwords - /// errorMessage will define why reset failed. - /// - /// The new password. - /// The reset token, typically supplied through a password reset email. - /// A Boolean indicating success or failure. - [Obsolete("Deprecate in 7.4.2, Use ChangePasswordByToken(int portalid, string username, string newPassword, string answer, string resetToken, out string errorMessage).. Scheduled removal in v10.0.0.")] - public static bool ChangePasswordByToken(int portalid, string username, string newPassword, string resetToken, out string errorMessage) - { - return ChangePasswordByToken(portalid, username, newPassword, string.Empty, resetToken, out errorMessage); - } - - [EditorBrowsable(EditorBrowsableState.Never)] - [Obsolete("Deprecated in DNN 6.1, keep this method to compatible with upgrade wizard.. Scheduled removal in v10.0.0.")] - public static UserInfo FillUserInfo(int portalId, IDataReader dr, bool closeDataReader) - { - UserInfo objUserInfo = null; - try - { - // read datareader - var bContinue = true; - if (closeDataReader) - { - bContinue = false; - if (dr.Read()) - { - // Ensure the data reader returned is valid - if (string.Equals(dr.GetName(0), "UserID", StringComparison.InvariantCultureIgnoreCase)) - { - bContinue = true; - } - } - } - - if (bContinue) - { - objUserInfo = new UserInfo - { - PortalID = portalId, - IsSuperUser = Null.SetNullBoolean(dr["IsSuperUser"]), - IsDeleted = Null.SetNullBoolean(dr["IsDeleted"]), - UserID = Null.SetNullInteger(dr["UserID"]), - FirstName = Null.SetNullString(dr["FirstName"]), - LastName = Null.SetNullString(dr["LastName"]), - DisplayName = Null.SetNullString(dr["DisplayName"]), - }; - objUserInfo.AffiliateID = Null.SetNullInteger(Null.SetNull(dr["AffiliateID"], objUserInfo.AffiliateID)); - objUserInfo.Username = Null.SetNullString(dr["Username"]); - GetUserMembership(objUserInfo); - objUserInfo.Email = Null.SetNullString(dr["Email"]); - objUserInfo.Membership.UpdatePassword = Null.SetNullBoolean(dr["UpdatePassword"]); - - var schema = dr.GetSchemaTable(); - if (schema != null) - { - if (schema.Select("ColumnName = 'PasswordResetExpiration'").Length > 0) - { - objUserInfo.PasswordResetExpiration = Null.SetNullDateTime(dr["PasswordResetExpiration"]); - } - - if (schema.Select("ColumnName = 'PasswordResetToken'").Length > 0) - { - objUserInfo.PasswordResetToken = Null.SetNullGuid(dr["PasswordResetToken"]); - } - } - - if (!objUserInfo.IsSuperUser) - { - objUserInfo.Membership.Approved = Null.SetNullBoolean(dr["Authorised"]); - } - } - } - finally - { - CBO.CloseDataReader(dr, closeDataReader); - } - - return objUserInfo; - } - } -} + /// The UserController class provides Business Layer methods for Users. + /// + /// DotNetNuke user management is base on asp.net membership provider, but the default implementation of these providers + /// do not satisfy the broad set of use cases which we need to support in DotNetNuke. so The dependency of DotNetNuke on the + /// MemberRole (ASP.NET 2 Membership) components will be abstracted into a DotNetNuke Membership Provider, in order to allow + /// developers complete flexibility in implementing alternate Membership approaches. + /// + /// This will allow for a number of enhancements to be added + /// Removal of dependence on the HttpContext + /// Support for Hashed Passwords + /// Support for Password Question and Answer + /// Enforce Password Complexity + /// Password Aging (Expiry) + /// Force Password Update + /// Enable/Disable Password Retrieval/Reset + /// CAPTCHA Support + /// Redirect after registration/login/logout + /// + /// + /// + public partial class UserController + { + [EditorBrowsable(EditorBrowsableState.Never)] + [DnnDeprecated(7, 2, 2, "This method has been replaced by UserController.MoveUserToPortal and UserController.CopyUserToPortal", RemovalVersion = 10)] + public static partial void CopyUserToPortal(UserInfo user, PortalInfo portal, bool mergeUser, bool deleteUser) + { + if (deleteUser) + { + MoveUserToPortal(user, portal, mergeUser); + } + else + { + CopyUserToPortal(user, portal, mergeUser); + } + } + + [EditorBrowsable(EditorBrowsableState.Never)] + [DnnDeprecated(7, 3, 0, "Replaced by UserController.Instance.GetCurrentUserInfo()", RemovalVersion = 10)] + public static partial UserInfo GetCurrentUserInfo() + { + return GetCurrentUserInternal(); + } + + /// + /// overload will validate the token and if valid change the password + /// it does not require an old password as it supports hashed passwords + /// errorMessage will define why reset failed. + /// + /// The new password. + /// The reset token, typically supplied through a password reset email. + /// A Boolean indicating success or failure. + [DnnDeprecated(7, 4, 2, "Use ChangePasswordByToken(int portalid, string username, string newPassword, string answer, string resetToken, out string errorMessage)", RemovalVersion = 10)] + public static partial bool ChangePasswordByToken(int portalid, string username, string newPassword, string resetToken, out string errorMessage) + { + return ChangePasswordByToken(portalid, username, newPassword, string.Empty, resetToken, out errorMessage); + } + + [EditorBrowsable(EditorBrowsableState.Never)] + [DnnDeprecated(6, 1, 0, "Keep this method to compatible with upgrade wizard", RemovalVersion = 10)] + public static partial UserInfo FillUserInfo(int portalId, IDataReader dr, bool closeDataReader) + { + UserInfo objUserInfo = null; + try + { + // read datareader + var bContinue = true; + if (closeDataReader) + { + bContinue = false; + if (dr.Read()) + { + // Ensure the data reader returned is valid + if (string.Equals(dr.GetName(0), "UserID", StringComparison.InvariantCultureIgnoreCase)) + { + bContinue = true; + } + } + } + + if (bContinue) + { + objUserInfo = new UserInfo + { + PortalID = portalId, + IsSuperUser = Null.SetNullBoolean(dr["IsSuperUser"]), + IsDeleted = Null.SetNullBoolean(dr["IsDeleted"]), + UserID = Null.SetNullInteger(dr["UserID"]), + FirstName = Null.SetNullString(dr["FirstName"]), + LastName = Null.SetNullString(dr["LastName"]), + DisplayName = Null.SetNullString(dr["DisplayName"]), + }; + objUserInfo.AffiliateID = Null.SetNullInteger(Null.SetNull(dr["AffiliateID"], objUserInfo.AffiliateID)); + objUserInfo.Username = Null.SetNullString(dr["Username"]); + GetUserMembership(objUserInfo); + objUserInfo.Email = Null.SetNullString(dr["Email"]); + objUserInfo.Membership.UpdatePassword = Null.SetNullBoolean(dr["UpdatePassword"]); + + var schema = dr.GetSchemaTable(); + if (schema != null) + { + if (schema.Select("ColumnName = 'PasswordResetExpiration'").Length > 0) + { + objUserInfo.PasswordResetExpiration = Null.SetNullDateTime(dr["PasswordResetExpiration"]); + } + + if (schema.Select("ColumnName = 'PasswordResetToken'").Length > 0) + { + objUserInfo.PasswordResetToken = Null.SetNullGuid(dr["PasswordResetToken"]); + } + } + + if (!objUserInfo.IsSuperUser) + { + objUserInfo.Membership.Approved = Null.SetNullBoolean(dr["Authorised"]); + } + } + } + finally + { + CBO.CloseDataReader(dr, closeDataReader); + } + + return objUserInfo; + } + } +} diff --git a/DNN Platform/Library/Properties/AssemblyInfo.cs b/DNN Platform/Library/Properties/AssemblyInfo.cs index ad3ef3fe9a0..710153dea39 100644 --- a/DNN Platform/Library/Properties/AssemblyInfo.cs +++ b/DNN Platform/Library/Properties/AssemblyInfo.cs @@ -35,6 +35,7 @@ [assembly: InternalsVisibleTo("DotNetNuke.Tests.Web")] [assembly: InternalsVisibleTo("DotNetNuke.Tests.Web.Mvc")] [assembly: InternalsVisibleTo("DotNetNuke.Tests.Urls")] +[assembly: InternalsVisibleTo("DotNetNuke.Tests.Mail")] [assembly: InternalsVisibleTo("DotNetNuke.Tests.Utilities")] [assembly: InternalsVisibleTo("DotNetNuke.Tests.Professional")] [assembly: InternalsVisibleTo("DotNetNuke.SiteExportImport")] diff --git a/DNN Platform/Library/Security/Membership/AspNetMembershipProvider.cs b/DNN Platform/Library/Security/Membership/AspNetMembershipProvider.cs index d570895ac34..124d450fcf3 100644 --- a/DNN Platform/Library/Security/Membership/AspNetMembershipProvider.cs +++ b/DNN Platform/Library/Security/Membership/AspNetMembershipProvider.cs @@ -23,6 +23,7 @@ namespace DotNetNuke.Security.Membership using DotNetNuke.Entities.Users.Membership; using DotNetNuke.Entities.Users.Social; using DotNetNuke.Instrumentation; + using DotNetNuke.Internal.SourceGenerators; using DotNetNuke.Services.Exceptions; // DNN-4016 @@ -30,7 +31,7 @@ namespace DotNetNuke.Security.Membership using DotNetNuke.Services.Log.EventLog; /// The AspNetMembershipProvider overrides the default MembershipProvider to provide an AspNet Membership Component (MemberRole) implementation. - public class AspNetMembershipProvider : MembershipProvider + public partial class AspNetMembershipProvider : MembershipProvider { private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(AspNetMembershipProvider)); private static Random random = new Random(); @@ -449,8 +450,8 @@ public override bool DeleteUser(UserInfo user) } /// - [Obsolete("Support for users online was removed in 8.x, other solutions exist outside of the DNN Platform. Scheduled removal in v11.0.0.")] - public override void DeleteUsersOnline(int timeWindow) + [DnnDeprecated(8, 0, 0, "Other solutions exist outside of the DNN Platform", RemovalVersion = 11)] + public override partial void DeleteUsersOnline(int timeWindow) { this.dataProvider.DeleteUsersOnline(timeWindow); } @@ -474,8 +475,8 @@ public override ArrayList GetDeletedUsers(int portalId) } /// - [Obsolete("Support for users online was removed in 8.x, other solutions exist outside of the DNN Platform. Scheduled removal in v11.0.0.")] - public override ArrayList GetOnlineUsers(int portalId) + [DnnDeprecated(8, 0, 0, "Other solutions exist outside of the DNN Platform", RemovalVersion = 11)] + public override partial ArrayList GetOnlineUsers(int portalId) { int totalRecords = 0; return FillUserCollection(portalId, this.dataProvider.GetOnlineUsers(portalId), ref totalRecords); @@ -770,8 +771,8 @@ public override ArrayList GetUsersByProfileProperty(int portalId, string propert } /// - [Obsolete("Support for users online was removed in 8.x, other solutions exist outside of the DNN Platform. Scheduled removal in v11.0.0.")] - public override bool IsUserOnline(UserInfo user) + [DnnDeprecated(8, 0, 0, "Other solutions exist outside of the DNN Platform", RemovalVersion = 11)] + public override partial bool IsUserOnline(UserInfo user) { bool isOnline = false; var objUsersOnline = new UserOnlineController(); @@ -976,8 +977,8 @@ public override void UpdateUser(UserInfo user) } /// - [Obsolete("Support for users online was removed in 8.x, other solutions exist outside of the DNN Platform. Scheduled removal in v11.0.0.")] - public override void UpdateUsersOnline(Hashtable userList) + [DnnDeprecated(8, 0, 0, "Other solutions exist outside of the DNN Platform", RemovalVersion = 11)] + public override partial void UpdateUsersOnline(Hashtable userList) { this.dataProvider.UpdateUsersOnline(userList); } diff --git a/DNN Platform/Library/Security/Membership/MembershipProvider.cs b/DNN Platform/Library/Security/Membership/MembershipProvider.cs index ba0f7c72927..ed3c4261587 100644 --- a/DNN Platform/Library/Security/Membership/MembershipProvider.cs +++ b/DNN Platform/Library/Security/Membership/MembershipProvider.cs @@ -146,24 +146,24 @@ public static MembershipProvider Instance() /// Deletes all UserOnline info from the database that has activity outside of the time window. /// Time Window in Minutes. - [Obsolete("Support for users online was removed in 8.x, other solutions exist outside of the DNN Platform. Scheduled removal in v11.0.0.")] + [Obsolete("Deprecated in DotNetNuke 8.0.0. Other solutions exist outside of the DNN Platform. Scheduled for removal in v11.0.0.")] public abstract void DeleteUsersOnline(int timeWindow); /// Gets a collection of Online Users. /// The Id of the Portal. /// An ArrayList of UserInfo objects. - [Obsolete("Support for users online was removed in 8.x, other solutions exist outside of the DNN Platform. Scheduled removal in v11.0.0.")] + [Obsolete("Deprecated in DotNetNuke 8.0.0. Other solutions exist outside of the DNN Platform. Scheduled for removal in v11.0.0.")] public abstract ArrayList GetOnlineUsers(int portalId); /// Gets whether the user in question is online. /// The user. /// A Boolean indicating whether the user is online. - [Obsolete("Support for users online was removed in 8.x, other solutions exist outside of the DNN Platform. Scheduled removal in v11.0.0.")] + [Obsolete("Deprecated in DotNetNuke 8.0.0. Other solutions exist outside of the DNN Platform. Scheduled for removal in v11.0.0.")] public abstract bool IsUserOnline(UserInfo user); /// Updates UserOnline info time window. /// List of users to update. - [Obsolete("Support for users online was removed in 8.x, other solutions exist outside of the DNN Platform. Scheduled removal in v11.0.0.")] + [Obsolete("Deprecated in DotNetNuke 8.0.0. Other solutions exist outside of the DNN Platform. Scheduled for removal in v11.0.0.")] public abstract void UpdateUsersOnline(Hashtable userList); // Legacy diff --git a/DNN Platform/Library/Security/Membership/UserLoginStatus.cs b/DNN Platform/Library/Security/Membership/UserLoginStatus.cs index d86876b2245..156d6970ef7 100644 --- a/DNN Platform/Library/Security/Membership/UserLoginStatus.cs +++ b/DNN Platform/Library/Security/Membership/UserLoginStatus.cs @@ -1,21 +1,21 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information - -namespace DotNetNuke.Security.Membership -{ - using System; +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information - public enum UserLoginStatus - { - LOGIN_FAILURE = 0, - LOGIN_SUCCESS = 1, - LOGIN_SUPERUSER = 2, - LOGIN_USERLOCKEDOUT = 3, +namespace DotNetNuke.Security.Membership +{ + using System; + + public enum UserLoginStatus + { + LOGIN_FAILURE = 0, + LOGIN_SUCCESS = 1, + LOGIN_SUPERUSER = 2, + LOGIN_USERLOCKEDOUT = 3, LOGIN_USERNOTAPPROVED = 4, - [Obsolete("Deprecated in 9.8.1. Scheduled removal in v11.0.0. No alternative method implemented.")] + [Obsolete("Deprecated in DotNetNuke 9.8.1. No alternative method implemented. Scheduled for removal in v11.0.0.")] LOGIN_INSECUREADMINPASSWORD = 5, - [Obsolete("Deprecated in 9.8.1. Scheduled removal in v11.0.0. No alternative method implemented.")] - LOGIN_INSECUREHOSTPASSWORD = 6, - } -} + [Obsolete("Deprecated in DotNetNuke 9.8.1. No alternative method implemented. Scheduled for removal in v11.0.0.")] + LOGIN_INSECUREHOSTPASSWORD = 6, + } +} diff --git a/DNN Platform/Library/Security/Permissions/PermissionController.cs b/DNN Platform/Library/Security/Permissions/PermissionController.cs index 2c74cb4eca6..284dc798f10 100644 --- a/DNN Platform/Library/Security/Permissions/PermissionController.cs +++ b/DNN Platform/Library/Security/Permissions/PermissionController.cs @@ -1,231 +1,232 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information -namespace DotNetNuke.Security.Permissions -{ - using System; - using System.Collections; - using System.Collections.Generic; - using System.Linq; - using System.Text; - - using DotNetNuke.Common; - using DotNetNuke.Common.Utilities; - using DotNetNuke.Data; - using DotNetNuke.Entities.Modules; - using DotNetNuke.Entities.Portals; - using DotNetNuke.Entities.Users; - using DotNetNuke.Security.Roles; +namespace DotNetNuke.Security.Permissions +{ + using System; + using System.Collections; + using System.Collections.Generic; + using System.Linq; + using System.Text; + + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Data; + using DotNetNuke.Entities.Modules; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Entities.Users; + using DotNetNuke.Internal.SourceGenerators; + using DotNetNuke.Security.Roles; using DotNetNuke.Services.Log.EventLog; - public class PermissionController - { - private static readonly DataProvider Provider = DataProvider.Instance(); - - public static string BuildPermissions(IList permissions, string permissionKey) - { - var permissionsBuilder = new StringBuilder(); - foreach (PermissionInfoBase permission in permissions) - { - if (permissionKey.Equals(permission.PermissionKey, StringComparison.InvariantCultureIgnoreCase)) - { - // Deny permissions are prefixed with a "!" - string prefix = !permission.AllowAccess ? "!" : string.Empty; - - // encode permission - string permissionString; - if (Null.IsNull(permission.UserID)) - { - permissionString = prefix + permission.RoleName + ";"; - } - else - { - permissionString = prefix + "[" + permission.UserID + "];"; - } - - // build permissions string ensuring that Deny permissions are inserted at the beginning and Grant permissions at the end - if (prefix == "!") - { - permissionsBuilder.Insert(0, permissionString); - } - else - { - permissionsBuilder.Append(permissionString); - } - } - } - - // get string - string permissionsString = permissionsBuilder.ToString(); - - // ensure leading delimiter - if (!permissionsString.StartsWith(";")) - { - permissionsString.Insert(0, ";"); - } - - return permissionsString; - } - - public static ArrayList GetPermissionsByFolder() - { - return new ArrayList(GetPermissions().Where(p => p.PermissionCode == "SYSTEM_FOLDER").ToArray()); - } - - public static ArrayList GetPermissionsByPortalDesktopModule() - { - return new ArrayList(GetPermissions().Where(p => p.PermissionCode == "SYSTEM_DESKTOPMODULE").ToArray()); - } - - public static ArrayList GetPermissionsByTab() - { - return new ArrayList(GetPermissions().Where(p => p.PermissionCode == "SYSTEM_TAB").ToArray()); - } - - public int AddPermission(PermissionInfo permission) - { - EventLogController.Instance.AddLog(permission, PortalController.Instance.GetCurrentPortalSettings(), UserController.Instance.GetCurrentUserInfo().UserID, string.Empty, EventLogController.EventLogType.PERMISSION_CREATED); - var permissionId = Convert.ToInt32(Provider.AddPermission( - permission.PermissionCode, - permission.ModuleDefID, - permission.PermissionKey, - permission.PermissionName, - UserController.Instance.GetCurrentUserInfo().UserID)); - - this.ClearCache(); - return permissionId; - } - - public void DeletePermission(int permissionID) - { - EventLogController.Instance.AddLog( - "PermissionID", - permissionID.ToString(), - PortalController.Instance.GetCurrentPortalSettings(), - UserController.Instance.GetCurrentUserInfo().UserID, - EventLogController.EventLogType.PERMISSION_DELETED); - Provider.DeletePermission(permissionID); - this.ClearCache(); - } - - public PermissionInfo GetPermission(int permissionID) - { - return GetPermissions().SingleOrDefault(p => p.PermissionID == permissionID); - } - - public ArrayList GetPermissionByCodeAndKey(string permissionCode, string permissionKey) - { - return new ArrayList(GetPermissions().Where(p => p.PermissionCode.Equals(permissionCode, StringComparison.InvariantCultureIgnoreCase) - && p.PermissionKey.Equals(permissionKey, StringComparison.InvariantCultureIgnoreCase)).ToArray()); - } - - public ArrayList GetPermissionsByModuleDefID(int moduleDefID) - { - return new ArrayList(GetPermissions().Where(p => p.ModuleDefID == moduleDefID).ToArray()); - } - - public ArrayList GetPermissionsByModule(int moduleId, int tabId) - { - var module = ModuleController.Instance.GetModule(moduleId, tabId, false); - - return new ArrayList(GetPermissions().Where(p => p.ModuleDefID == module.ModuleDefID || p.PermissionCode == "SYSTEM_MODULE_DEFINITION").ToArray()); - } - - public void UpdatePermission(PermissionInfo permission) - { - EventLogController.Instance.AddLog(permission, PortalController.Instance.GetCurrentPortalSettings(), UserController.Instance.GetCurrentUserInfo().UserID, string.Empty, EventLogController.EventLogType.PERMISSION_UPDATED); - Provider.UpdatePermission( - permission.PermissionID, - permission.PermissionCode, - permission.ModuleDefID, - permission.PermissionKey, - permission.PermissionName, - UserController.Instance.GetCurrentUserInfo().UserID); - this.ClearCache(); - } - - public T RemapPermission(T permission, int portalId) - where T : PermissionInfoBase - { - PermissionInfo permissionInfo = this.GetPermissionByCodeAndKey(permission.PermissionCode, permission.PermissionKey).ToArray().Cast().FirstOrDefault(); - T result = null; - - if (permissionInfo != null) - { - int roleID = int.MinValue; - int userID = int.MinValue; - - if (string.IsNullOrEmpty(permission.RoleName)) - { - UserInfo user = UserController.GetUserByName(portalId, permission.Username); - if (user != null) - { - userID = user.UserID; - } - } - else - { - switch (permission.RoleName) - { - case Globals.glbRoleAllUsersName: - roleID = Convert.ToInt32(Globals.glbRoleAllUsers); - break; - case Globals.glbRoleUnauthUserName: - roleID = Convert.ToInt32(Globals.glbRoleUnauthUser); - break; - default: - RoleInfo role = RoleController.Instance.GetRole(portalId, r => r.RoleName == permission.RoleName); - if (role != null) - { - roleID = role.RoleID; - } - - break; - } - } - - // if role was found add, otherwise ignore - if (roleID != int.MinValue || userID != int.MinValue) - { - permission.PermissionID = permissionInfo.PermissionID; - if (roleID != int.MinValue) - { - permission.RoleID = roleID; - } - - if (userID != int.MinValue) - { - permission.UserID = userID; - } - - result = permission; - } - } - - return result; - } - - [Obsolete("Deprecated in DNN 7.3.0. Replaced by GetPermissionsByModule(int, int). Scheduled removal in v10.0.0.")] - public ArrayList GetPermissionsByModuleID(int moduleId) - { - var module = ModuleController.Instance.GetModule(moduleId, Null.NullInteger, true); - - return this.GetPermissionsByModuleDefID(module.ModuleDefID); - } - - private static IEnumerable GetPermissions() - { - return CBO.GetCachedObject>( - new CacheItemArgs( - DataCache.PermissionsCacheKey, - DataCache.PermissionsCacheTimeout, - DataCache.PermissionsCachePriority), - c => CBO.FillCollection(Provider.ExecuteReader("GetPermissions"))); - } - - private void ClearCache() - { - DataCache.RemoveCache(DataCache.PermissionsCacheKey); - } - } -} + public partial class PermissionController + { + private static readonly DataProvider Provider = DataProvider.Instance(); + + public static string BuildPermissions(IList permissions, string permissionKey) + { + var permissionsBuilder = new StringBuilder(); + foreach (PermissionInfoBase permission in permissions) + { + if (permissionKey.Equals(permission.PermissionKey, StringComparison.InvariantCultureIgnoreCase)) + { + // Deny permissions are prefixed with a "!" + string prefix = !permission.AllowAccess ? "!" : string.Empty; + + // encode permission + string permissionString; + if (Null.IsNull(permission.UserID)) + { + permissionString = prefix + permission.RoleName + ";"; + } + else + { + permissionString = prefix + "[" + permission.UserID + "];"; + } + + // build permissions string ensuring that Deny permissions are inserted at the beginning and Grant permissions at the end + if (prefix == "!") + { + permissionsBuilder.Insert(0, permissionString); + } + else + { + permissionsBuilder.Append(permissionString); + } + } + } + + // get string + string permissionsString = permissionsBuilder.ToString(); + + // ensure leading delimiter + if (!permissionsString.StartsWith(";")) + { + permissionsString.Insert(0, ";"); + } + + return permissionsString; + } + + public static ArrayList GetPermissionsByFolder() + { + return new ArrayList(GetPermissions().Where(p => p.PermissionCode == "SYSTEM_FOLDER").ToArray()); + } + + public static ArrayList GetPermissionsByPortalDesktopModule() + { + return new ArrayList(GetPermissions().Where(p => p.PermissionCode == "SYSTEM_DESKTOPMODULE").ToArray()); + } + + public static ArrayList GetPermissionsByTab() + { + return new ArrayList(GetPermissions().Where(p => p.PermissionCode == "SYSTEM_TAB").ToArray()); + } + + public int AddPermission(PermissionInfo permission) + { + EventLogController.Instance.AddLog(permission, PortalController.Instance.GetCurrentPortalSettings(), UserController.Instance.GetCurrentUserInfo().UserID, string.Empty, EventLogController.EventLogType.PERMISSION_CREATED); + var permissionId = Convert.ToInt32(Provider.AddPermission( + permission.PermissionCode, + permission.ModuleDefID, + permission.PermissionKey, + permission.PermissionName, + UserController.Instance.GetCurrentUserInfo().UserID)); + + this.ClearCache(); + return permissionId; + } + + public void DeletePermission(int permissionID) + { + EventLogController.Instance.AddLog( + "PermissionID", + permissionID.ToString(), + PortalController.Instance.GetCurrentPortalSettings(), + UserController.Instance.GetCurrentUserInfo().UserID, + EventLogController.EventLogType.PERMISSION_DELETED); + Provider.DeletePermission(permissionID); + this.ClearCache(); + } + + public PermissionInfo GetPermission(int permissionID) + { + return GetPermissions().SingleOrDefault(p => p.PermissionID == permissionID); + } + + public ArrayList GetPermissionByCodeAndKey(string permissionCode, string permissionKey) + { + return new ArrayList(GetPermissions().Where(p => p.PermissionCode.Equals(permissionCode, StringComparison.InvariantCultureIgnoreCase) + && p.PermissionKey.Equals(permissionKey, StringComparison.InvariantCultureIgnoreCase)).ToArray()); + } + + public ArrayList GetPermissionsByModuleDefID(int moduleDefID) + { + return new ArrayList(GetPermissions().Where(p => p.ModuleDefID == moduleDefID).ToArray()); + } + + public ArrayList GetPermissionsByModule(int moduleId, int tabId) + { + var module = ModuleController.Instance.GetModule(moduleId, tabId, false); + + return new ArrayList(GetPermissions().Where(p => p.ModuleDefID == module.ModuleDefID || p.PermissionCode == "SYSTEM_MODULE_DEFINITION").ToArray()); + } + + public void UpdatePermission(PermissionInfo permission) + { + EventLogController.Instance.AddLog(permission, PortalController.Instance.GetCurrentPortalSettings(), UserController.Instance.GetCurrentUserInfo().UserID, string.Empty, EventLogController.EventLogType.PERMISSION_UPDATED); + Provider.UpdatePermission( + permission.PermissionID, + permission.PermissionCode, + permission.ModuleDefID, + permission.PermissionKey, + permission.PermissionName, + UserController.Instance.GetCurrentUserInfo().UserID); + this.ClearCache(); + } + + public T RemapPermission(T permission, int portalId) + where T : PermissionInfoBase + { + PermissionInfo permissionInfo = this.GetPermissionByCodeAndKey(permission.PermissionCode, permission.PermissionKey).ToArray().Cast().FirstOrDefault(); + T result = null; + + if (permissionInfo != null) + { + int roleID = int.MinValue; + int userID = int.MinValue; + + if (string.IsNullOrEmpty(permission.RoleName)) + { + UserInfo user = UserController.GetUserByName(portalId, permission.Username); + if (user != null) + { + userID = user.UserID; + } + } + else + { + switch (permission.RoleName) + { + case Globals.glbRoleAllUsersName: + roleID = Convert.ToInt32(Globals.glbRoleAllUsers); + break; + case Globals.glbRoleUnauthUserName: + roleID = Convert.ToInt32(Globals.glbRoleUnauthUser); + break; + default: + RoleInfo role = RoleController.Instance.GetRole(portalId, r => r.RoleName == permission.RoleName); + if (role != null) + { + roleID = role.RoleID; + } + + break; + } + } + + // if role was found add, otherwise ignore + if (roleID != int.MinValue || userID != int.MinValue) + { + permission.PermissionID = permissionInfo.PermissionID; + if (roleID != int.MinValue) + { + permission.RoleID = roleID; + } + + if (userID != int.MinValue) + { + permission.UserID = userID; + } + + result = permission; + } + } + + return result; + } + + [DnnDeprecated(7, 3, 0, "Replaced by GetPermissionsByModule(int, int)", RemovalVersion = 10)] + public partial ArrayList GetPermissionsByModuleID(int moduleId) + { + var module = ModuleController.Instance.GetModule(moduleId, Null.NullInteger, true); + + return this.GetPermissionsByModuleDefID(module.ModuleDefID); + } + + private static IEnumerable GetPermissions() + { + return CBO.GetCachedObject>( + new CacheItemArgs( + DataCache.PermissionsCacheKey, + DataCache.PermissionsCacheTimeout, + DataCache.PermissionsCachePriority), + c => CBO.FillCollection(Provider.ExecuteReader("GetPermissions"))); + } + + private void ClearCache() + { + DataCache.RemoveCache(DataCache.PermissionsCacheKey); + } + } +} diff --git a/DNN Platform/Library/Security/PortalSecurity.cs b/DNN Platform/Library/Security/PortalSecurity.cs index e9fafbe1fcb..78dcc99de73 100644 --- a/DNN Platform/Library/Security/PortalSecurity.cs +++ b/DNN Platform/Library/Security/PortalSecurity.cs @@ -18,6 +18,7 @@ namespace DotNetNuke.Security using DotNetNuke.Entities.Portals; using DotNetNuke.Entities.Users; using DotNetNuke.Entities.Users.Social; + using DotNetNuke.Internal.SourceGenerators; using DotNetNuke.Security.Cookies; using DotNetNuke.Services.Cryptography; @@ -95,14 +96,17 @@ public class PortalSecurity public enum FilterFlag { MultiLine = 1, - [Obsolete("Deprecated in 9.8.1. Scheduled removal in v11.0.0. A direct call to WebUtility.HtmlEncode should be used")] + + [Obsolete("Deprecated in DotNetNuke 9.8.1. A direct call to WebUtility.HtmlEncode should be used. Scheduled for removal in v11.0.0.")] NoMarkup = 2, - [Obsolete("Deprecated in 9.8.1. Scheduled removal in v11.0.0. A direct call to WebUtility.HtmlEncode should be used")] + + [Obsolete("Deprecated in DotNetNuke 9.8.1. A direct call to WebUtility.HtmlEncode should be used. Scheduled for removal in v11.0.0.")] NoScripting = 4, - [Obsolete("Deprecated in 9.8.1. Scheduled removal in v11.0.0. Parameterized SQL should be preferred for SQL Injection protection")] + + [Obsolete("Deprecated in DotNetNuke 9.8.1. Parameterized SQL should be preferred for SQL Injection protection. Scheduled for removal in v11.0.0.")] NoSQL = 8, - [Obsolete("Deprecated in 9.8.1. Scheduled removal in v11.0.0. Individual string replacement should be completed")] + [Obsolete("Deprecated in DotNetNuke 9.8.1. Individual string replacement should be completed. Scheduled for removal in v11.0.0.")] NoAngleBrackets = 16, NoProfanity = 32, } @@ -133,6 +137,9 @@ private enum RoleType Owner = 3, } + /// + /// Forces the secure connection. + /// public static void ForceSecureConnection() { // get current url @@ -159,6 +166,11 @@ public static void ForceSecureConnection() } } + /// + /// Gets the cookie domain for the portal group or from web.config. + /// + /// The portal identifier. + /// Cookie domain for the portal group or from web.config. public static string GetCookieDomain(int portalId) { string cookieDomain = string.Empty; @@ -189,6 +201,13 @@ public static string GetCookieDomain(int portalId) return cookieDomain; } + /// + /// Determines whether the current user is denied for the given role(s). + /// + /// The semicolon separated list of roles. + /// + /// true if the current user is denied from the provided specified roles; otherwise, false. + /// public static bool IsDenied(string roles) { UserInfo objUserInfo = UserController.Instance.GetCurrentUserInfo(); @@ -196,6 +215,15 @@ public static bool IsDenied(string roles) return IsDenied(objUserInfo, settings, roles); } + /// + /// Determines whether the specified user is denied for the given roles. + /// + /// The user information. + /// The settings. + /// The semicolon separated list of roles. + /// + /// true if the specified user is denied; otherwise, false. + /// public static bool IsDenied(UserInfo objUserInfo, PortalSettings settings, string roles) { // super user always has full access @@ -234,6 +262,13 @@ public static bool IsDenied(UserInfo objUserInfo, PortalSettings settings, strin return isDenied; } + /// + /// Determines whether the current user belonds to the specified role. + /// + /// The role name. + /// + /// true if user belongs to the specified role; otherwise, false. + /// public static bool IsInRole(string role) { if (!string.IsNullOrEmpty(role) && role == Globals.glbRoleUnauthUserName && !HttpContext.Current.Request.IsAuthenticated) @@ -244,6 +279,13 @@ public static bool IsInRole(string role) return IsInRoles(UserController.Instance.GetCurrentUserInfo(), PortalController.Instance.GetCurrentPortalSettings(), role); } + /// + /// Determines whether the current user belongs to the specified roles. + /// + /// The semicolon separated list of roles. + /// + /// true if user belongs to the specified roles; otherwise, false. + /// public static bool IsInRoles(string roles) { UserInfo objUserInfo = UserController.Instance.GetCurrentUserInfo(); @@ -251,6 +293,15 @@ public static bool IsInRoles(string roles) return IsInRoles(objUserInfo, settings, roles); } + /// + /// Determines whether the provided user belongs to the specified roles. + /// + /// The user information. + /// The settings. + /// The semicolon separated list of roles. + /// + /// true if the provided user belongs to the specific roles; otherwise, false. + /// public static bool IsInRoles(UserInfo objUserInfo, PortalSettings settings, string roles) { // super user always has full access @@ -276,6 +327,13 @@ public static bool IsInRoles(UserInfo objUserInfo, PortalSettings settings, stri return isInRoles; } + /// + /// Determines whether the specified user is a friend of the current user. + /// + /// The user identifier. + /// + /// true if the specified user is a friend of the current user; otherwise, false. + /// public static bool IsFriend(int userId) { UserInfo objUserInfo = UserController.Instance.GetCurrentUserInfo(); @@ -283,6 +341,13 @@ public static bool IsFriend(int userId) return IsInRoles(objUserInfo, settings, RoleFriendPrefix + userId); } + /// + /// Determines whether the specified user is a follower of the current user. + /// + /// The user identifier. + /// + /// true if the specified user is a follower of the current user; otherwise, false. + /// public static bool IsFollower(int userId) { UserInfo objUserInfo = UserController.Instance.GetCurrentUserInfo(); @@ -290,6 +355,13 @@ public static bool IsFollower(int userId) return IsInRoles(objUserInfo, settings, RoleFollowerPrefix + userId); } + /// + /// Determines whether the specified user is an owner. + /// + /// The user identifier. + /// + /// true if the specified user is an owner; otherwise, false. + /// public static bool IsOwner(int userId) { UserInfo objUserInfo = UserController.Instance.GetCurrentUserInfo(); @@ -311,21 +383,45 @@ public string CreateKey(int numBytes) } } + /// + /// Decrypts the provided string data using a supplied key. + /// + /// The encryption key. + /// The encrypted data. + /// The decrypted string. public string Decrypt(string strKey, string strData) { return CryptographyProvider.Instance().DecryptParameter(strData, strKey); } + /// + /// Decrypts a string using a provided passphrase. + /// + /// The encrypted message. + /// The passphrase. + /// The decrypted string. public string DecryptString(string message, string passphrase) { return CryptographyProvider.Instance().DecryptString(message, passphrase); } + /// + /// Encrypts the specified key. + /// + /// The key. + /// The data. + /// The encrypted string. public string Encrypt(string key, string data) { return CryptographyProvider.Instance().EncryptParameter(data, key); } + /// + /// Encrypts a string using a provided passphrase. + /// + /// The message. + /// The passphrase. + /// The encrypted string. public string EncryptString(string message, string passphrase) { return CryptographyProvider.Instance().EncryptString(message, passphrase); @@ -496,6 +592,11 @@ public string Remove(string inputString, ConfigType configType, string configSou return inputString; } + /// + /// Signs the provided user in and sets a persistent login cookie if needed. + /// + /// The user info. + /// if set to true [create persistent cookie]. public void SignIn(UserInfo user, bool createPersistentCookie) { if (PortalController.IsMemberOfPortalGroup(user.PortalID) || createPersistentCookie) @@ -570,6 +671,9 @@ public void SignIn(UserInfo user, bool createPersistentCookie) HttpContext.Current.Items["DNN_UserSignIn"] = true; } + /// + /// Signs the current user out. + /// public void SignOut() { InvalidateAspNetSession(HttpContext.Current); diff --git a/DNN Platform/Library/Services/Authentication/AuthenticationLoginBase.cs b/DNN Platform/Library/Services/Authentication/AuthenticationLoginBase.cs index db8c4eff19e..1d4468c640e 100644 --- a/DNN Platform/Library/Services/Authentication/AuthenticationLoginBase.cs +++ b/DNN Platform/Library/Services/Authentication/AuthenticationLoginBase.cs @@ -8,13 +8,14 @@ namespace DotNetNuke.Services.Authentication using DotNetNuke.Common.Utilities; using DotNetNuke.Entities.Modules; + using DotNetNuke.Internal.SourceGenerators; using DotNetNuke.Services.UserRequest; /// /// The AuthenticationLoginBase class provides a bas class for Authentication /// Login controls. /// - public abstract class AuthenticationLoginBase : UserModuleBase + public abstract partial class AuthenticationLoginBase : UserModuleBase { /// Initializes a new instance of the class. protected AuthenticationLoginBase() @@ -60,8 +61,8 @@ public virtual bool SupportsRegistration /// Gets or sets the Redirect Url for this control. public string RedirectURL { get; set; } - [Obsolete("Deprecated in 9.2.0. Use UserRequestIPAddressController.Instance.GetUserRequestIPAddress. Scheduled removal in v11.0.0.")] - public static string GetIPAddress() + [DnnDeprecated(9, 2, 0, "Use UserRequestIPAddressController.Instance.GetUserRequestIPAddress")] + public static partial string GetIPAddress() { return UserRequestIPAddressController.Instance.GetUserRequestIPAddress(new HttpRequestWrapper(HttpContext.Current.Request)); } diff --git a/DNN Platform/Library/Services/ClientCapability/ClientCapability.cs b/DNN Platform/Library/Services/ClientCapability/ClientCapability.cs index a408bbeed83..030b1768b39 100644 --- a/DNN Platform/Library/Services/ClientCapability/ClientCapability.cs +++ b/DNN Platform/Library/Services/ClientCapability/ClientCapability.cs @@ -45,7 +45,7 @@ public ClientCapability() public bool SupportsFlash { get; set; } /// - [Obsolete("This method is not memory efficient and should be avoided as the Match class now exposes an accessor keyed on property name. Scheduled removal in v10.0.0.")] + [Obsolete("Deprecated in DotNetNuke 8.0.0. This method is not memory efficient and should be avoided as the Match class now exposes an accessor keyed on property name. Scheduled for removal in v10.0.0.")] public IDictionary Capabilities { get diff --git a/DNN Platform/Library/Services/ClientCapability/IClientCapability.cs b/DNN Platform/Library/Services/ClientCapability/IClientCapability.cs index 7c2e0ea3795..39c62e365f7 100644 --- a/DNN Platform/Library/Services/ClientCapability/IClientCapability.cs +++ b/DNN Platform/Library/Services/ClientCapability/IClientCapability.cs @@ -46,7 +46,7 @@ public interface IClientCapability bool SupportsFlash { get; set; } /// Gets or sets a key-value collection containing all capabilities supported by requester. - [Obsolete("This method is not memory efficient and should be avoided as the Match class now exposes an accessor keyed on property name. Scheduled removal in v10.0.0.")] + [Obsolete("Deprecated in DotNetNuke 8.0.0. This method is not memory efficient and should be avoided as the Match class now exposes an accessor keyed on property name. Scheduled for removal in v10.0.0.")] IDictionary Capabilities { get; set; } /// Gets or sets the request preferred HTML DTD. diff --git a/DNN Platform/Library/Services/DependencyInjection/IScopeAccessor.cs b/DNN Platform/Library/Services/DependencyInjection/IScopeAccessor.cs index 92f02d18291..42f704084a0 100644 --- a/DNN Platform/Library/Services/DependencyInjection/IScopeAccessor.cs +++ b/DNN Platform/Library/Services/DependencyInjection/IScopeAccessor.cs @@ -4,39 +4,13 @@ namespace DotNetNuke.Services.DependencyInjection { - using System; - using System.Collections; - using System.Web; - - using DotNetNuke.Common.Extensions; using Microsoft.Extensions.DependencyInjection; + /// A contract specifying the ability to access an instance. public interface IScopeAccessor - { + { + /// Gets the scope. + /// The scope, or if there is no scope to get. IServiceScope GetScope(); } - - public class ScopeAccessor : IScopeAccessor - { - private static Func fallbackGetContextItems = () => HttpContext.Current?.Items; - - private Func getContextItems; - - /// Initializes a new instance of the class. - public ScopeAccessor() - { - this.getContextItems = fallbackGetContextItems; - } - - /// - public IServiceScope GetScope() - { - return HttpContextDependencyInjectionExtensions.GetScope(this.getContextItems()); - } - - internal void SetContextItemsFunc(Func getContextItems) - { - this.getContextItems = getContextItems ?? fallbackGetContextItems; - } - } } diff --git a/DNN Platform/Library/Services/DependencyInjection/ScopeAccessor.cs b/DNN Platform/Library/Services/DependencyInjection/ScopeAccessor.cs new file mode 100644 index 00000000000..272d548f465 --- /dev/null +++ b/DNN Platform/Library/Services/DependencyInjection/ScopeAccessor.cs @@ -0,0 +1,19 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + +namespace DotNetNuke.Services.DependencyInjection; + +using DotNetNuke.Common; +using DotNetNuke.Common.Extensions; +using Microsoft.Extensions.DependencyInjection; + +/// An implementation using . +public class ScopeAccessor : IScopeAccessor +{ + /// + public IServiceScope GetScope() + { + return HttpContextSource.Current.GetScope(); + } +} diff --git a/DNN Platform/Library/Services/EventQueue/EventQueueController.cs b/DNN Platform/Library/Services/EventQueue/EventQueueController.cs index 923ebdffc0b..00671173be0 100644 --- a/DNN Platform/Library/Services/EventQueue/EventQueueController.cs +++ b/DNN Platform/Library/Services/EventQueue/EventQueueController.cs @@ -9,6 +9,7 @@ namespace DotNetNuke.Services.EventQueue using DotNetNuke.Common.Utilities; using DotNetNuke.Data; using DotNetNuke.Framework; + using DotNetNuke.Internal.SourceGenerators; using DotNetNuke.Services.EventQueue.Config; using DotNetNuke.Services.Log.EventLog; @@ -39,7 +40,7 @@ namespace DotNetNuke.Services.EventQueue /// } /// /// - public class EventQueueController + public partial class EventQueueController { /// Gets the messages. /// Name of the event. @@ -174,8 +175,8 @@ public static bool SendMessage(EventMessage message, string eventName) return success; } - [Obsolete("This method is obsolete. Use Sendmessage(message, eventName) instead. Scheduled removal in v10.0.0.")] - public bool SendMessage(EventMessage message, string eventName, bool encryptMessage) + [DnnDeprecated(7, 0, 0, "Use Sendmessage(message, eventName) instead", RemovalVersion = 10)] + public partial bool SendMessage(EventMessage message, string eventName, bool encryptMessage) { return SendMessage(message, eventName); } diff --git a/DNN Platform/Library/Services/FileSystem/FolderInfo.cs b/DNN Platform/Library/Services/FileSystem/FolderInfo.cs index 97d60c340ff..73a166d2685 100644 --- a/DNN Platform/Library/Services/FileSystem/FolderInfo.cs +++ b/DNN Platform/Library/Services/FileSystem/FolderInfo.cs @@ -1,36 +1,36 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information -namespace DotNetNuke.Services.FileSystem -{ - using System; - using System.Data; - using System.Linq; - using System.Web; - using System.Xml.Serialization; - - using DotNetNuke.Common; - using DotNetNuke.Common.Utilities; - using DotNetNuke.Entities; - using DotNetNuke.Entities.Modules; - using DotNetNuke.Entities.Portals; +namespace DotNetNuke.Services.FileSystem +{ + using System; + using System.Data; + using System.Linq; + using System.Web; + using System.Xml.Serialization; + + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities; + using DotNetNuke.Entities.Modules; + using DotNetNuke.Entities.Portals; using DotNetNuke.Security.Permissions; using Newtonsoft.Json; - [XmlRoot("folder", IsNullable = false)] - [Serializable] - public class FolderInfo : BaseEntityInfo, IHydratable, IFolderInfo - { - // local property declarations - private string displayName; - private string displayPath; - private FolderPermissionCollection folderPermissions; + [XmlRoot("folder", IsNullable = false)] + [Serializable] + public class FolderInfo : BaseEntityInfo, IHydratable, IFolderInfo + { + // local property declarations + private string displayName; + private string displayPath; + private FolderPermissionCollection folderPermissions; private int folderMappingId; /// Initializes a new instance of the class. - public FolderInfo() - : this(false) - { + public FolderInfo() + : this(false) + { } /// Initializes a new instance of the class. @@ -40,10 +40,10 @@ public FolderInfo() /// /// /// - [Obsolete("Deprecated in DNN 7.1. Use the parameterless constructor and object initializers. Scheduled removal in v10.0.0.")] - public FolderInfo(int portalId, string folderpath, int storageLocation, bool isProtected, bool isCached, DateTime lastUpdated) - : this(Guid.NewGuid(), portalId, folderpath, storageLocation, isProtected, isCached, lastUpdated) - { + [Obsolete("Deprecated in DotNetNuke 7.1.0. Use the parameterless constructor and object initializers. Scheduled for removal in v10.0.0.")] + public FolderInfo(int portalId, string folderpath, int storageLocation, bool isProtected, bool isCached, DateTime lastUpdated) + : this(Guid.NewGuid(), portalId, folderpath, storageLocation, isProtected, isCached, lastUpdated) + { } /// Initializes a new instance of the class. @@ -54,280 +54,280 @@ public FolderInfo(int portalId, string folderpath, int storageLocation, bool isP /// /// /// - [Obsolete("Deprecated in DNN 7.1. Use the parameterless constructor and object initializers. Scheduled removal in v10.0.0.")] - public FolderInfo(Guid uniqueId, int portalId, string folderpath, int storageLocation, bool isProtected, bool isCached, DateTime lastUpdated) - { - this.FolderID = Null.NullInteger; - this.UniqueId = uniqueId; - this.VersionGuid = Guid.NewGuid(); - this.WorkflowID = Null.NullInteger; - - this.PortalID = portalId; - this.FolderPath = folderpath; - this.StorageLocation = storageLocation; - this.IsProtected = isProtected; - this.IsCached = isCached; - this.LastUpdated = lastUpdated; + [Obsolete("Deprecated in DotNetNuke 7.1.0. Use the parameterless constructor and object initializers. Scheduled for removal in v10.0.0.")] + public FolderInfo(Guid uniqueId, int portalId, string folderpath, int storageLocation, bool isProtected, bool isCached, DateTime lastUpdated) + { + this.FolderID = Null.NullInteger; + this.UniqueId = uniqueId; + this.VersionGuid = Guid.NewGuid(); + this.WorkflowID = Null.NullInteger; + + this.PortalID = portalId; + this.FolderPath = folderpath; + this.StorageLocation = storageLocation; + this.IsProtected = isProtected; + this.IsCached = isCached; + this.LastUpdated = lastUpdated; } /// Initializes a new instance of the class. /// - internal FolderInfo(bool initialiseEmptyPermissions) - { - this.FolderID = Null.NullInteger; - this.UniqueId = Guid.NewGuid(); - this.VersionGuid = Guid.NewGuid(); - this.WorkflowID = Null.NullInteger; - if (initialiseEmptyPermissions) - { - this.folderPermissions = new FolderPermissionCollection(); - } + internal FolderInfo(bool initialiseEmptyPermissions) + { + this.FolderID = Null.NullInteger; + this.UniqueId = Guid.NewGuid(); + this.VersionGuid = Guid.NewGuid(); + this.WorkflowID = Null.NullInteger; + if (initialiseEmptyPermissions) + { + this.folderPermissions = new FolderPermissionCollection(); + } } /// - [XmlElement("uniqueid")] + [XmlElement("uniqueid")] public Guid UniqueId { get; set; } /// - [XmlElement("versionguid")] + [XmlElement("versionguid")] public Guid VersionGuid { get; set; } /// - [XmlElement("foldername")] - public string FolderName - { - get - { - string folderName = PathUtils.Instance.RemoveTrailingSlash(this.FolderPath); - if (folderName.Length > 0 && folderName.LastIndexOf("/", StringComparison.Ordinal) > -1) - { - folderName = folderName.Substring(folderName.LastIndexOf("/", StringComparison.Ordinal) + 1); - } - - return folderName; - } - } - - /// Gets a value indicating whether the folder has any child subfolder. - [XmlElement("haschildren")] - public bool HasChildren - { - get - { - return FolderManager.Instance.GetFolders(this).Any(); - } - } - - /// Gets or sets a reference to the active Workflow for the folder. - [XmlElement("workflowid")] - public int WorkflowID { get; set; } - - /// Gets or sets a reference to the parent folder. - [XmlElement("parentid")] + [XmlElement("foldername")] + public string FolderName + { + get + { + string folderName = PathUtils.Instance.RemoveTrailingSlash(this.FolderPath); + if (folderName.Length > 0 && folderName.LastIndexOf("/", StringComparison.Ordinal) > -1) + { + folderName = folderName.Substring(folderName.LastIndexOf("/", StringComparison.Ordinal) + 1); + } + + return folderName; + } + } + + /// Gets a value indicating whether the folder has any child subfolder. + [XmlElement("haschildren")] + public bool HasChildren + { + get + { + return FolderManager.Instance.GetFolders(this).Any(); + } + } + + /// Gets or sets a reference to the active Workflow for the folder. + [XmlElement("workflowid")] + public int WorkflowID { get; set; } + + /// Gets or sets a reference to the parent folder. + [XmlElement("parentid")] public int ParentID { get; set; } /// [XmlElement("physicalpath")] - public string PhysicalPath - { - get - { - string physicalPath; - PortalSettings portalSettings = null; - if (HttpContext.Current != null) - { - portalSettings = PortalController.Instance.GetCurrentPortalSettings(); - } - - if (this.PortalID == Null.NullInteger) - { - physicalPath = Globals.HostMapPath + this.FolderPath; - } - else - { - if (portalSettings == null || portalSettings.PortalId != this.PortalID) - { - // Get the PortalInfo based on the Portalid - var portal = PortalController.Instance.GetPortal(this.PortalID); - - physicalPath = portal.HomeDirectoryMapPath + this.FolderPath; - } - else - { - physicalPath = portalSettings.HomeDirectoryMapPath + this.FolderPath; - } - } - - return physicalPath.Replace("/", "\\"); - } + public string PhysicalPath + { + get + { + string physicalPath; + PortalSettings portalSettings = null; + if (HttpContext.Current != null) + { + portalSettings = PortalController.Instance.GetCurrentPortalSettings(); + } + + if (this.PortalID == Null.NullInteger) + { + physicalPath = Globals.HostMapPath + this.FolderPath; + } + else + { + if (portalSettings == null || portalSettings.PortalId != this.PortalID) + { + // Get the PortalInfo based on the Portalid + var portal = PortalController.Instance.GetPortal(this.PortalID); + + physicalPath = portal.HomeDirectoryMapPath + this.FolderPath; + } + else + { + physicalPath = portalSettings.HomeDirectoryMapPath + this.FolderPath; + } + } + + return physicalPath.Replace("/", "\\"); + } } /// - [XmlElement("portalid")] + [XmlElement("portalid")] public int PortalID { get; set; } /// - [XmlElement("storagelocation")] + [XmlElement("storagelocation")] public int StorageLocation { get; set; } /// [XmlElement("folderpermissions")] - public FolderPermissionCollection FolderPermissions - { - get - { - return this.folderPermissions ?? (this.folderPermissions = new FolderPermissionCollection(FolderPermissionController.GetFolderPermissionsCollectionByFolder(this.PortalID, this.FolderPath))); - } + public FolderPermissionCollection FolderPermissions + { + get + { + return this.folderPermissions ?? (this.folderPermissions = new FolderPermissionCollection(FolderPermissionController.GetFolderPermissionsCollectionByFolder(this.PortalID, this.FolderPath))); + } } /// - public bool IsStorageSecure - { - get - { - var folderMapping = FolderMappingController.Instance.GetFolderMapping(this.PortalID, this.FolderMappingID); - return FolderProvider.Instance(folderMapping.FolderProviderType).IsStorageSecure; - } + public bool IsStorageSecure + { + get + { + var folderMapping = FolderMappingController.Instance.GetFolderMapping(this.PortalID, this.FolderMappingID); + return FolderProvider.Instance(folderMapping.FolderProviderType).IsStorageSecure; + } } /// - [XmlElement("folderid")] + [XmlElement("folderid")] public int FolderID { get; set; } /// - [XmlElement("displayname")] - public string DisplayName - { - get - { - if (string.IsNullOrEmpty(this.displayName)) - { - this.displayName = this.FolderName; - } - - return this.displayName; - } - - set - { - this.displayName = value; - } + [XmlElement("displayname")] + public string DisplayName + { + get + { + if (string.IsNullOrEmpty(this.displayName)) + { + this.displayName = this.FolderName; + } + + return this.displayName; + } + + set + { + this.displayName = value; + } } /// - [XmlElement("folderpath")] + [XmlElement("folderpath")] public string FolderPath { get; set; } /// - [XmlElement("displaypath")] - public string DisplayPath - { - get - { - if (string.IsNullOrEmpty(this.displayPath)) - { - this.displayPath = this.FolderPath; - } - - return this.displayPath; - } - - set - { - this.displayPath = value; - } + [XmlElement("displaypath")] + public string DisplayPath + { + get + { + if (string.IsNullOrEmpty(this.displayPath)) + { + this.displayPath = this.FolderPath; + } + + return this.displayPath; + } + + set + { + this.displayPath = value; + } } /// - [XmlElement("iscached")] + [XmlElement("iscached")] public bool IsCached { get; set; } /// - [XmlElement("isprotected")] - public bool IsProtected { get; set; } - - /// Gets or sets a value indicating whether file versions are active for the folder. - [XmlElement("isversioned")] - public bool IsVersioned { get; set; } - - /// Gets or sets the path this folder is mapped on its provider file system. - [XmlElement("mappedpath")] + [XmlElement("isprotected")] + public bool IsProtected { get; set; } + + /// Gets or sets a value indicating whether file versions are active for the folder. + [XmlElement("isversioned")] + public bool IsVersioned { get; set; } + + /// Gets or sets the path this folder is mapped on its provider file system. + [XmlElement("mappedpath")] public string MappedPath { get; set; } /// [XmlIgnore] - [JsonIgnore] + [JsonIgnore] public DateTime LastUpdated { get; set; } /// - public int FolderMappingID - { - get - { - if (this.folderMappingId == 0) - { - switch (this.StorageLocation) - { - case (int)FolderController.StorageLocationTypes.InsecureFileSystem: - this.folderMappingId = FolderMappingController.Instance.GetFolderMapping(this.PortalID, "Standard").FolderMappingID; - break; - case (int)FolderController.StorageLocationTypes.SecureFileSystem: - this.folderMappingId = FolderMappingController.Instance.GetFolderMapping(this.PortalID, "Secure").FolderMappingID; - break; - case (int)FolderController.StorageLocationTypes.DatabaseSecure: - this.folderMappingId = FolderMappingController.Instance.GetFolderMapping(this.PortalID, "Database").FolderMappingID; - break; - default: - this.folderMappingId = FolderMappingController.Instance.GetDefaultFolderMapping(this.PortalID).FolderMappingID; - break; - } - } - - return this.folderMappingId; - } - - set - { - this.folderMappingId = value; - } - } - - /// Gets or sets and sets the Key ID. - /// An Integer. + public int FolderMappingID + { + get + { + if (this.folderMappingId == 0) + { + switch (this.StorageLocation) + { + case (int)FolderController.StorageLocationTypes.InsecureFileSystem: + this.folderMappingId = FolderMappingController.Instance.GetFolderMapping(this.PortalID, "Standard").FolderMappingID; + break; + case (int)FolderController.StorageLocationTypes.SecureFileSystem: + this.folderMappingId = FolderMappingController.Instance.GetFolderMapping(this.PortalID, "Secure").FolderMappingID; + break; + case (int)FolderController.StorageLocationTypes.DatabaseSecure: + this.folderMappingId = FolderMappingController.Instance.GetFolderMapping(this.PortalID, "Database").FolderMappingID; + break; + default: + this.folderMappingId = FolderMappingController.Instance.GetDefaultFolderMapping(this.PortalID).FolderMappingID; + break; + } + } + + return this.folderMappingId; + } + + set + { + this.folderMappingId = value; + } + } + + /// Gets or sets and sets the Key ID. + /// An Integer. [XmlIgnore] - [JsonIgnore] - public int KeyID - { - get - { - return this.FolderID; - } - - set - { - this.FolderID = value; - } - } - - /// Fills a FolderInfo from a Data Reader. - /// The Data Reader to use. - public void Fill(IDataReader dr) - { - this.FolderID = Null.SetNullInteger(dr["FolderID"]); - this.UniqueId = Null.SetNullGuid(dr["UniqueId"]); - this.VersionGuid = Null.SetNullGuid(dr["VersionGuid"]); - this.PortalID = Null.SetNullInteger(dr["PortalID"]); - this.FolderPath = Null.SetNullString(dr["FolderPath"]); - this.MappedPath = Null.SetNullString(dr["MappedPath"]); - this.IsCached = Null.SetNullBoolean(dr["IsCached"]); - this.IsProtected = Null.SetNullBoolean(dr["IsProtected"]); - this.StorageLocation = Null.SetNullInteger(dr["StorageLocation"]); - this.LastUpdated = Null.SetNullDateTime(dr["LastUpdated"]); - this.FolderMappingID = Null.SetNullInteger(dr["FolderMappingID"]); - this.IsVersioned = Null.SetNullBoolean(dr["IsVersioned"]); - this.WorkflowID = Null.SetNullInteger(dr["WorkflowID"]); - this.ParentID = Null.SetNullInteger(dr["ParentID"]); - this.FillBaseProperties(dr); - } - } -} + [JsonIgnore] + public int KeyID + { + get + { + return this.FolderID; + } + + set + { + this.FolderID = value; + } + } + + /// Fills a FolderInfo from a Data Reader. + /// The Data Reader to use. + public void Fill(IDataReader dr) + { + this.FolderID = Null.SetNullInteger(dr["FolderID"]); + this.UniqueId = Null.SetNullGuid(dr["UniqueId"]); + this.VersionGuid = Null.SetNullGuid(dr["VersionGuid"]); + this.PortalID = Null.SetNullInteger(dr["PortalID"]); + this.FolderPath = Null.SetNullString(dr["FolderPath"]); + this.MappedPath = Null.SetNullString(dr["MappedPath"]); + this.IsCached = Null.SetNullBoolean(dr["IsCached"]); + this.IsProtected = Null.SetNullBoolean(dr["IsProtected"]); + this.StorageLocation = Null.SetNullInteger(dr["StorageLocation"]); + this.LastUpdated = Null.SetNullDateTime(dr["LastUpdated"]); + this.FolderMappingID = Null.SetNullInteger(dr["FolderMappingID"]); + this.IsVersioned = Null.SetNullBoolean(dr["IsVersioned"]); + this.WorkflowID = Null.SetNullInteger(dr["WorkflowID"]); + this.ParentID = Null.SetNullInteger(dr["ParentID"]); + this.FillBaseProperties(dr); + } + } +} diff --git a/DNN Platform/Library/Services/FileSystem/FolderManager.cs b/DNN Platform/Library/Services/FileSystem/FolderManager.cs index b1e4dcbf9cf..f5cc561a11d 100644 --- a/DNN Platform/Library/Services/FileSystem/FolderManager.cs +++ b/DNN Platform/Library/Services/FileSystem/FolderManager.cs @@ -25,6 +25,7 @@ namespace DotNetNuke.Services.FileSystem using DotNetNuke.Entities.Portals; using DotNetNuke.Entities.Users; using DotNetNuke.Instrumentation; + using DotNetNuke.Internal.SourceGenerators; using DotNetNuke.Security.Permissions; using DotNetNuke.Services.FileSystem.EventArgs; using DotNetNuke.Services.FileSystem.Internal; @@ -33,7 +34,7 @@ namespace DotNetNuke.Services.FileSystem using Localization = DotNetNuke.Services.Localization.Localization; /// Exposes methods to manage folders. - public class FolderManager : ComponentBase, IFolderManager + public partial class FolderManager : ComponentBase, IFolderManager { private const string DefaultUsersFoldersPath = "Users"; private const string DefaultMappedPathSetting = "DefaultMappedPath"; @@ -771,8 +772,8 @@ public virtual void SetFolderPermissions(IFolderInfo folder, int administratorRo /// The new folder path. /// The moved folder. [EditorBrowsable(EditorBrowsableState.Never)] - [Obsolete("Deprecated in DNN 7.1. It has been replaced by FolderManager.Instance.MoveFolder(IFolderInfo folder, IFolderInfo destinationFolder) . Scheduled removal in v10.0.0.")] - public virtual IFolderInfo MoveFolder(IFolderInfo folder, string newFolderPath) + [DnnDeprecated(7, 1, 0, "It has been replaced by FolderManager.Instance.MoveFolder(IFolderInfo folder, IFolderInfo destinationFolder)", RemovalVersion = 10)] + public virtual partial IFolderInfo MoveFolder(IFolderInfo folder, string newFolderPath) { Requires.NotNull("folder", folder); Requires.NotNullOrEmpty("newFolderPath", newFolderPath); diff --git a/DNN Platform/Library/Services/FileSystem/IFileManager.cs b/DNN Platform/Library/Services/FileSystem/IFileManager.cs index 62229576f53..f33cfe779ee 100644 --- a/DNN Platform/Library/Services/FileSystem/IFileManager.cs +++ b/DNN Platform/Library/Services/FileSystem/IFileManager.cs @@ -17,7 +17,7 @@ namespace DotNetNuke.Services.FileSystem public interface IFileManager { /// Gets the system defined content types. - [Obsolete("Deprecated in DNN 7.4.2. It has been replaced by FileContentTypeManager.Instance.ContentTypes. Scheduled removal in v10.0.0.")] + [Obsolete("Deprecated in DotNetNuke 7.4.2. It has been replaced by FileContentTypeManager.Instance.ContentTypes. Scheduled for removal in v10.0.0.")] IDictionary ContentTypes { get; } /// Gets current user's file upload extension whitelist. @@ -101,7 +101,7 @@ public interface IFileManager /// Gets the Content Type for the specified file extension. /// The file extension. /// The Content Type for the specified extension. - [Obsolete("Deprecated in DNN 7.4.2. It has been replaced by FileContentTypeManager.Instance.GetContentType(string extension). Scheduled removal in v10.0.0.")] + [Obsolete("Deprecated in DotNetNuke 7.4.2. It has been replaced by FileContentTypeManager.Instance.GetContentType(string extension). Scheduled for removal in v10.0.0.")] string GetContentType(string extension); /// Gets the file metadata for the specified file. diff --git a/DNN Platform/Library/Services/FileSystem/IFolderManager.cs b/DNN Platform/Library/Services/FileSystem/IFolderManager.cs index 662cefb1fbf..14a8bfb2802 100644 --- a/DNN Platform/Library/Services/FileSystem/IFolderManager.cs +++ b/DNN Platform/Library/Services/FileSystem/IFolderManager.cs @@ -2,224 +2,224 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information -namespace DotNetNuke.Services.FileSystem -{ - using System; - using System.Collections.Generic; - using System.ComponentModel; - - using DotNetNuke.Entities.Users; - using DotNetNuke.Security.Permissions; - - /// - /// Do not implement. This interface is meant for reference and unit test purposes only. - /// There is no guarantee that this interface will not change. - /// - public interface IFolderManager - { - /// Gets the alias name of the personal User Folder. - string MyFolderName { get; } - - /// Adds read permissions for all users to the specified folder. - /// The folder to add the permission to. - /// Used as base class for FolderPermissionInfo when there is no read permission already defined. - void AddAllUserReadPermission(IFolderInfo folder, PermissionInfo permission); - - /// Creates a new folder using the provided folder path and mapping. - /// The folder mapping to use. - /// The path of the new folder. - /// The added folder. - IFolderInfo AddFolder(FolderMappingInfo folderMapping, string folderPath); - - /// Creates a new folder using the provided folder path and mapping. - /// The folder mapping to use. - /// The path of the new folder. - /// The path of the new folder in the provider. - /// The added folder. - IFolderInfo AddFolder(FolderMappingInfo folderMapping, string folderPath, string mappedPath); - - /// - /// Creates a new folder in the given portal using the provided folder path. - /// The same mapping than the parent folder will be used to create this folder. So this method have to be used only to create subfolders. - /// - /// The portal identifier. - /// The path of the new folder. - /// The added folder. - IFolderInfo AddFolder(int portalId, string folderPath); - - /// Sets folder permissions to the given folder by copying parent folder permissions. - /// The folder to copy permissions to. - void CopyParentFolderPermissions(IFolderInfo folder); - - /// Deletes the specified folder. - /// The folder to delete. - void DeleteFolder(IFolderInfo folder); - - /// Deletes the specified folder. - /// The folder identifier. - void DeleteFolder(int folderId); - - /// Unlink the specified folder. - /// The folder to unlink. - void UnlinkFolder(IFolderInfo folder); - - /// Delete the specified folder and all its content. - /// The folder to delete>. - /// A collection with all not deleted subfolders. - void DeleteFolder(IFolderInfo folder, ICollection notDeletedSubfolders); - - /// Checks the existence of the specified folder in the specified portal. - /// The portal where to check the existence of the folder. - /// The path of folder to check the existence of. - /// A boolean value indicating whether the folder exists or not in the specified portal. - bool FolderExists(int portalId, string folderPath); - - /// Gets the files contained in the specified folder. - /// The folder from which to retrieve the files. - /// The list of files contained in the specified folder. - IEnumerable GetFiles(IFolderInfo folder); - - /// Gets the files contained in the specified folder. - /// The folder from which to retrieve the files. - /// Whether or not to include all the subfolders. - /// The list of files contained in the specified folder. - IEnumerable GetFiles(IFolderInfo folder, bool recursive); - - /// Gets the files contained in the specified folder. - /// The folder from which to retrieve the files. - /// Whether or not to include all the subfolders. - /// Indicates if the file is retrieved from All files or from Published files. - /// The list of files contained in the specified folder. - IEnumerable GetFiles(IFolderInfo folder, bool recursive, bool retrieveUnpublishedFiles); - - /// Search the files contained in the specified folder, for a matching pattern. - /// The folder from which to retrieve the files. - /// The patter to search for. - /// Whether or not to include all the subfolders. - /// The list of files contained in the specified folder. - IEnumerable SearchFiles(IFolderInfo folder, string pattern, bool recursive = false); - - /// Gets the list of Standard folders the specified user has the provided permissions. - /// The user info. - /// The permissions the folders have to met. - /// The list of Standard folders the specified user has the provided permissions. - /// This method is used to support legacy behaviours and situations where we know the file/folder is in the file system. - IEnumerable GetFileSystemFolders(UserInfo user, string permissions); - - /// Gets a folder entity by providing a portal identifier and folder identifier. - /// The identifier of the folder. - /// The folder entity or null if the folder cannot be located. - IFolderInfo GetFolder(int folderId); - - /// Gets a folder entity by providing a portal identifier and folder path. - /// The portal where the folder exists. - /// The path of the folder. - /// The folder entity or null if the folder cannot be located. - IFolderInfo GetFolder(int portalId, string folderPath); - - /// Gets a folder entity by providing its unique id. - /// The unique id of the folder. - /// The folder entity or null if the folder cannot be located. - IFolderInfo GetFolder(Guid uniqueId); - - /// Get the users folder. - /// the user. - /// FolderInfo for the users folder. - IFolderInfo GetUserFolder(UserInfo userInfo); - - /// Gets the list of subfolders for the specified folder. - /// The folder to get the list of subfolders. - /// The list of subfolders for the specified folder. - IEnumerable GetFolders(IFolderInfo parentFolder); - - /// Gets the sorted list of folders of the provided portal. - /// The portal identifier. - /// The sorted list of folders of the provided portal. - IEnumerable GetFolders(int portalId); - - /// Gets the sorted list of folders of the provided portal. - /// The portal identifier. - /// True = Read from Cache, False = Read from DB. - /// The sorted list of folders of the provided portal. - IEnumerable GetFolders(int portalId, bool useCache); - - /// Gets the sorted list of folders that match the provided permissions in the specified portal. - /// The portal identifier. - /// The permissions to match. - /// The user identifier to be used to check permissions. - /// The list of folders that match the provided permissions in the specified portal. - IEnumerable GetFolders(int portalId, string permissions, int userId); - - /// Gets the list of folders the specified user has read permissions. - /// The user info. - /// The list of folders the specified user has read permissions. - IEnumerable GetFolders(UserInfo user); - - /// Gets the list of folders the specified user has the provided permissions. - /// The user info. - /// The permissions the folders have to met. - /// The list of folders the specified user has the provided permissions. - IEnumerable GetFolders(UserInfo user, string permissions); - - /// Moves the specified folder and its contents to a new location. - /// The folder to move. - /// The destination folder. - /// The moved folder. - IFolderInfo MoveFolder(IFolderInfo folder, IFolderInfo destinationFolder); - - /// Renames the specified folder by setting the new provided folder name. - /// The folder to rename. - /// The new name to apply to the folder. - void RenameFolder(IFolderInfo folder, string newFolderName); - - /// Sets specific folder permissions for the given role to the given folder. - /// The folder to set permission to. - /// The id of the permission to assign. - /// The role to assign the permission to. - void SetFolderPermission(IFolderInfo folder, int permissionId, int roleId); - - /// Sets specific folder permissions for the given role/user to the given folder. - /// The folder to set permission to. - /// The id of the permission to assign. - /// The role to assign the permission to. - /// The user to assign the permission to. - void SetFolderPermission(IFolderInfo folder, int permissionId, int roleId, int userId); - - /// Sets folder permissions for administrator role to the given folder. - /// The folder to set permission to. - /// The administrator role id to assign the permission to. - void SetFolderPermissions(IFolderInfo folder, int administratorRoleId); - - /// Synchronizes the entire folder tree for the specified portal. - /// The portal identifier. - /// The number of folder collisions. - int Synchronize(int portalId); - - /// Synchronizes the specified folder, its files and its subfolders. - /// The portal identifier. - /// The relative path of the folder. - /// The number of folder collisions. - int Synchronize(int portalId, string relativePath); - - /// Synchronizes the specified folder, its files and, optionally, its subfolders. - /// The portal identifier. - /// The relative path of the folder. - /// Indicates if the synchronization has to be recursive. - /// Indicates if files need to be synchronized. - /// The number of folder collisions. - int Synchronize(int portalId, string relativePath, bool isRecursive, bool syncFiles); - - /// Updates metadata of the specified folder. - /// The folder to update. - /// The updated folder. - IFolderInfo UpdateFolder(IFolderInfo folder); - - /// Moves the specified folder and its contents to a new location. - /// The folder to move. - /// The new folder path. - /// The moved folder. - [EditorBrowsable(EditorBrowsableState.Never)] - [Obsolete("Deprecated in DNN 7.1. It has been replaced by FolderManager.Instance.MoveFolder(IFolderInfo folder, IFolderInfo destinationFolder) . Scheduled removal in v10.0.0.")] - IFolderInfo MoveFolder(IFolderInfo folder, string newFolderPath); - } -} +namespace DotNetNuke.Services.FileSystem +{ + using System; + using System.Collections.Generic; + using System.ComponentModel; + + using DotNetNuke.Entities.Users; + using DotNetNuke.Security.Permissions; + + /// + /// Do not implement. This interface is meant for reference and unit test purposes only. + /// There is no guarantee that this interface will not change. + /// + public interface IFolderManager + { + /// Gets the alias name of the personal User Folder. + string MyFolderName { get; } + + /// Adds read permissions for all users to the specified folder. + /// The folder to add the permission to. + /// Used as base class for FolderPermissionInfo when there is no read permission already defined. + void AddAllUserReadPermission(IFolderInfo folder, PermissionInfo permission); + + /// Creates a new folder using the provided folder path and mapping. + /// The folder mapping to use. + /// The path of the new folder. + /// The added folder. + IFolderInfo AddFolder(FolderMappingInfo folderMapping, string folderPath); + + /// Creates a new folder using the provided folder path and mapping. + /// The folder mapping to use. + /// The path of the new folder. + /// The path of the new folder in the provider. + /// The added folder. + IFolderInfo AddFolder(FolderMappingInfo folderMapping, string folderPath, string mappedPath); + + /// + /// Creates a new folder in the given portal using the provided folder path. + /// The same mapping than the parent folder will be used to create this folder. So this method have to be used only to create subfolders. + /// + /// The portal identifier. + /// The path of the new folder. + /// The added folder. + IFolderInfo AddFolder(int portalId, string folderPath); + + /// Sets folder permissions to the given folder by copying parent folder permissions. + /// The folder to copy permissions to. + void CopyParentFolderPermissions(IFolderInfo folder); + + /// Deletes the specified folder. + /// The folder to delete. + void DeleteFolder(IFolderInfo folder); + + /// Deletes the specified folder. + /// The folder identifier. + void DeleteFolder(int folderId); + + /// Unlink the specified folder. + /// The folder to unlink. + void UnlinkFolder(IFolderInfo folder); + + /// Delete the specified folder and all its content. + /// The folder to delete>. + /// A collection with all not deleted subfolders. + void DeleteFolder(IFolderInfo folder, ICollection notDeletedSubfolders); + + /// Checks the existence of the specified folder in the specified portal. + /// The portal where to check the existence of the folder. + /// The path of folder to check the existence of. + /// A boolean value indicating whether the folder exists or not in the specified portal. + bool FolderExists(int portalId, string folderPath); + + /// Gets the files contained in the specified folder. + /// The folder from which to retrieve the files. + /// The list of files contained in the specified folder. + IEnumerable GetFiles(IFolderInfo folder); + + /// Gets the files contained in the specified folder. + /// The folder from which to retrieve the files. + /// Whether or not to include all the subfolders. + /// The list of files contained in the specified folder. + IEnumerable GetFiles(IFolderInfo folder, bool recursive); + + /// Gets the files contained in the specified folder. + /// The folder from which to retrieve the files. + /// Whether or not to include all the subfolders. + /// Indicates if the file is retrieved from All files or from Published files. + /// The list of files contained in the specified folder. + IEnumerable GetFiles(IFolderInfo folder, bool recursive, bool retrieveUnpublishedFiles); + + /// Search the files contained in the specified folder, for a matching pattern. + /// The folder from which to retrieve the files. + /// The patter to search for. + /// Whether or not to include all the subfolders. + /// The list of files contained in the specified folder. + IEnumerable SearchFiles(IFolderInfo folder, string pattern, bool recursive = false); + + /// Gets the list of Standard folders the specified user has the provided permissions. + /// The user info. + /// The permissions the folders have to met. + /// The list of Standard folders the specified user has the provided permissions. + /// This method is used to support legacy behaviours and situations where we know the file/folder is in the file system. + IEnumerable GetFileSystemFolders(UserInfo user, string permissions); + + /// Gets a folder entity by providing a portal identifier and folder identifier. + /// The identifier of the folder. + /// The folder entity or null if the folder cannot be located. + IFolderInfo GetFolder(int folderId); + + /// Gets a folder entity by providing a portal identifier and folder path. + /// The portal where the folder exists. + /// The path of the folder. + /// The folder entity or null if the folder cannot be located. + IFolderInfo GetFolder(int portalId, string folderPath); + + /// Gets a folder entity by providing its unique id. + /// The unique id of the folder. + /// The folder entity or null if the folder cannot be located. + IFolderInfo GetFolder(Guid uniqueId); + + /// Get the users folder. + /// the user. + /// FolderInfo for the users folder. + IFolderInfo GetUserFolder(UserInfo userInfo); + + /// Gets the list of subfolders for the specified folder. + /// The folder to get the list of subfolders. + /// The list of subfolders for the specified folder. + IEnumerable GetFolders(IFolderInfo parentFolder); + + /// Gets the sorted list of folders of the provided portal. + /// The portal identifier. + /// The sorted list of folders of the provided portal. + IEnumerable GetFolders(int portalId); + + /// Gets the sorted list of folders of the provided portal. + /// The portal identifier. + /// True = Read from Cache, False = Read from DB. + /// The sorted list of folders of the provided portal. + IEnumerable GetFolders(int portalId, bool useCache); + + /// Gets the sorted list of folders that match the provided permissions in the specified portal. + /// The portal identifier. + /// The permissions to match. + /// The user identifier to be used to check permissions. + /// The list of folders that match the provided permissions in the specified portal. + IEnumerable GetFolders(int portalId, string permissions, int userId); + + /// Gets the list of folders the specified user has read permissions. + /// The user info. + /// The list of folders the specified user has read permissions. + IEnumerable GetFolders(UserInfo user); + + /// Gets the list of folders the specified user has the provided permissions. + /// The user info. + /// The permissions the folders have to met. + /// The list of folders the specified user has the provided permissions. + IEnumerable GetFolders(UserInfo user, string permissions); + + /// Moves the specified folder and its contents to a new location. + /// The folder to move. + /// The destination folder. + /// The moved folder. + IFolderInfo MoveFolder(IFolderInfo folder, IFolderInfo destinationFolder); + + /// Renames the specified folder by setting the new provided folder name. + /// The folder to rename. + /// The new name to apply to the folder. + void RenameFolder(IFolderInfo folder, string newFolderName); + + /// Sets specific folder permissions for the given role to the given folder. + /// The folder to set permission to. + /// The id of the permission to assign. + /// The role to assign the permission to. + void SetFolderPermission(IFolderInfo folder, int permissionId, int roleId); + + /// Sets specific folder permissions for the given role/user to the given folder. + /// The folder to set permission to. + /// The id of the permission to assign. + /// The role to assign the permission to. + /// The user to assign the permission to. + void SetFolderPermission(IFolderInfo folder, int permissionId, int roleId, int userId); + + /// Sets folder permissions for administrator role to the given folder. + /// The folder to set permission to. + /// The administrator role id to assign the permission to. + void SetFolderPermissions(IFolderInfo folder, int administratorRoleId); + + /// Synchronizes the entire folder tree for the specified portal. + /// The portal identifier. + /// The number of folder collisions. + int Synchronize(int portalId); + + /// Synchronizes the specified folder, its files and its subfolders. + /// The portal identifier. + /// The relative path of the folder. + /// The number of folder collisions. + int Synchronize(int portalId, string relativePath); + + /// Synchronizes the specified folder, its files and, optionally, its subfolders. + /// The portal identifier. + /// The relative path of the folder. + /// Indicates if the synchronization has to be recursive. + /// Indicates if files need to be synchronized. + /// The number of folder collisions. + int Synchronize(int portalId, string relativePath, bool isRecursive, bool syncFiles); + + /// Updates metadata of the specified folder. + /// The folder to update. + /// The updated folder. + IFolderInfo UpdateFolder(IFolderInfo folder); + + /// Moves the specified folder and its contents to a new location. + /// The folder to move. + /// The new folder path. + /// The moved folder. + [EditorBrowsable(EditorBrowsableState.Never)] + [Obsolete("Deprecated in DotNetNuke 7.1.0. It has been replaced by FolderManager.Instance.MoveFolder(IFolderInfo folder, IFolderInfo destinationFolder). Scheduled for removal in v10.0.0.")] + IFolderInfo MoveFolder(IFolderInfo folder, string newFolderPath); + } +} diff --git a/DNN Platform/Library/Services/GeneratedImage/IPCount.cs b/DNN Platform/Library/Services/GeneratedImage/IPCount.cs index 676ee29a2c5..c2490fb9cb4 100644 --- a/DNN Platform/Library/Services/GeneratedImage/IPCount.cs +++ b/DNN Platform/Library/Services/GeneratedImage/IPCount.cs @@ -2,36 +2,37 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information -namespace DotNetNuke.Services.GeneratedImage -{ - using System; - using System.Collections.Generic; - using System.IO; - using System.Threading; - using System.Web; - using System.Web.Hosting; - - using DotNetNuke.Services.UserRequest; - - public class IPCount - { - private const string TempFileExtension = ".tmp"; - private const string CacheAppRelativePath = @"~\App_Data\_ipcount\"; - private static readonly object PurgeQueuedLock = new object(); - private static readonly object FileLock = new object(); - private static string cachePath; - private static bool purgeQueued; - private static TimeSpan purgeInterval; - - static IPCount() - { - PurgeInterval = new TimeSpan(0, 10, 0); - MaxCount = 500; - CachePath = HostingEnvironment.MapPath(CacheAppRelativePath); - } - - public static string CachePath - { +namespace DotNetNuke.Services.GeneratedImage +{ + using System; + using System.Collections.Generic; + using System.IO; + using System.Threading; + using System.Web; + using System.Web.Hosting; + + using DotNetNuke.Internal.SourceGenerators; + using DotNetNuke.Services.UserRequest; + + public partial class IPCount + { + private const string TempFileExtension = ".tmp"; + private const string CacheAppRelativePath = @"~\App_Data\_ipcount\"; + private static readonly object PurgeQueuedLock = new object(); + private static readonly object FileLock = new object(); + private static string cachePath; + private static bool purgeQueued; + private static TimeSpan purgeInterval; + + static IPCount() + { + PurgeInterval = new TimeSpan(0, 10, 0); + MaxCount = 500; + CachePath = HostingEnvironment.MapPath(CacheAppRelativePath); + } + + public static string CachePath + { get { return cachePath; @@ -39,154 +40,154 @@ public static string CachePath set { - if (string.IsNullOrEmpty(value)) - { - throw new ArgumentNullException(nameof(value)); + if (string.IsNullOrEmpty(value)) + { + throw new ArgumentNullException(nameof(value)); } - if (!Directory.Exists(value)) - { - Directory.CreateDirectory(value); + if (!Directory.Exists(value)) + { + Directory.CreateDirectory(value); } cachePath = value; } - } - - public static TimeSpan PurgeInterval - { - get - { - return purgeInterval; - } - - set - { - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } - - if (value.Ticks < 0) - { - throw new ArgumentOutOfRangeException(nameof(value)); - } - - purgeInterval = value; - } - } - - public static int MaxCount { get; set; } - - private static DateTime LastPurge - { - get - { - var lastPurge = DateTime.Now; - if (File.Exists(CachePath + "_lastpurge")) - { - var fi = new FileInfo(CachePath + "_lastpurge"); - lastPurge = fi.LastWriteTime; - } - else - { - File.WriteAllText(CachePath + "_lastpurge", string.Empty); - } - - return lastPurge; - } - - set - { - File.WriteAllText(CachePath + "_lastpurge", string.Empty); - } - } - - public static bool CheckIp(string ipAddress) - { - var now = DateTime.Now; - if (!purgeQueued && now.Subtract(LastPurge) > PurgeInterval) - { - lock (PurgeQueuedLock) - { - if (!purgeQueued) - { - purgeQueued = true; - - var files = new DirectoryInfo(CachePath).GetFiles(); - var threshold = DateTime.Now.Subtract(PurgeInterval); - var toTryDeleteAgain = new List(); - foreach (var fileinfo in files) - { - if (fileinfo.Name.ToLowerInvariant() != "_lastpurge" && fileinfo.LastWriteTime < threshold) - { - try - { - fileinfo.Delete(); - } - catch (Exception) - { - toTryDeleteAgain.Add(fileinfo); - } - } - } - - Thread.Sleep(0); - foreach (var fileinfo in toTryDeleteAgain) - { - try - { - fileinfo.Delete(); - } - catch (Exception) - { - // do nothing at this point, try to delete file during next purge - } - } - - LastPurge = DateTime.Now; - - purgeQueued = false; - } - } - } - - var path = BuildFilePath(ipAddress); - var count = 1; - lock (FileLock) - { - if (File.Exists(path)) - { - var strCount = File.ReadAllText(path); - if (int.TryParse(strCount, out count)) - { - if (count > MaxCount) - { - return false; - } - - count++; - } - } - - File.WriteAllText(path, count.ToString()); - return true; - } - } - - /// method to get Client ip address. - /// IP Address of visitor. - [Obsolete("Deprecated in 9.2.0. Use UserRequestIPAddressController.Instance.GetUserRequestIPAddress. Scheduled removal in v11.0.0.")] - public static string GetVisitorIPAddress(HttpContextBase context) - { - return UserRequestIPAddressController.Instance.GetUserRequestIPAddress(context.Request); - } - - private static string BuildFilePath(string ipAddress) - { - // it takes only the IP address without PORT for the file name - var fileName = ipAddress.Split(':')[0]; - return CachePath + fileName + TempFileExtension; - } - } -} + } + + public static TimeSpan PurgeInterval + { + get + { + return purgeInterval; + } + + set + { + if (value == null) + { + throw new ArgumentNullException(nameof(value)); + } + + if (value.Ticks < 0) + { + throw new ArgumentOutOfRangeException(nameof(value)); + } + + purgeInterval = value; + } + } + + public static int MaxCount { get; set; } + + private static DateTime LastPurge + { + get + { + var lastPurge = DateTime.Now; + if (File.Exists(CachePath + "_lastpurge")) + { + var fi = new FileInfo(CachePath + "_lastpurge"); + lastPurge = fi.LastWriteTime; + } + else + { + File.WriteAllText(CachePath + "_lastpurge", string.Empty); + } + + return lastPurge; + } + + set + { + File.WriteAllText(CachePath + "_lastpurge", string.Empty); + } + } + + public static bool CheckIp(string ipAddress) + { + var now = DateTime.Now; + if (!purgeQueued && now.Subtract(LastPurge) > PurgeInterval) + { + lock (PurgeQueuedLock) + { + if (!purgeQueued) + { + purgeQueued = true; + + var files = new DirectoryInfo(CachePath).GetFiles(); + var threshold = DateTime.Now.Subtract(PurgeInterval); + var toTryDeleteAgain = new List(); + foreach (var fileinfo in files) + { + if (fileinfo.Name.ToLowerInvariant() != "_lastpurge" && fileinfo.LastWriteTime < threshold) + { + try + { + fileinfo.Delete(); + } + catch (Exception) + { + toTryDeleteAgain.Add(fileinfo); + } + } + } + + Thread.Sleep(0); + foreach (var fileinfo in toTryDeleteAgain) + { + try + { + fileinfo.Delete(); + } + catch (Exception) + { + // do nothing at this point, try to delete file during next purge + } + } + + LastPurge = DateTime.Now; + + purgeQueued = false; + } + } + } + + var path = BuildFilePath(ipAddress); + var count = 1; + lock (FileLock) + { + if (File.Exists(path)) + { + var strCount = File.ReadAllText(path); + if (int.TryParse(strCount, out count)) + { + if (count > MaxCount) + { + return false; + } + + count++; + } + } + + File.WriteAllText(path, count.ToString()); + return true; + } + } + + /// method to get Client ip address. + /// IP Address of visitor. + [DnnDeprecated(9, 2, 0, "Use UserRequestIPAddressController.Instance.GetUserRequestIPAddress")] + public static partial string GetVisitorIPAddress(HttpContextBase context) + { + return UserRequestIPAddressController.Instance.GetUserRequestIPAddress(context.Request); + } + + private static string BuildFilePath(string ipAddress) + { + // it takes only the IP address without PORT for the file name + var fileName = ipAddress.Split(':')[0]; + return CachePath + fileName + TempFileExtension; + } + } +} diff --git a/DNN Platform/Library/Services/Installer/InstallFile.cs b/DNN Platform/Library/Services/Installer/InstallFile.cs index a269b0e5c06..ab61274d120 100644 --- a/DNN Platform/Library/Services/Installer/InstallFile.cs +++ b/DNN Platform/Library/Services/Installer/InstallFile.cs @@ -9,11 +9,13 @@ namespace DotNetNuke.Services.Installer using System.IO.Compression; using System.Text.RegularExpressions; + using DotNetNuke.Internal.SourceGenerators; + using ICSharpCode.SharpZipLib.Zip; /// The InstallFile class represents a single file in an Installer Package. [Serializable] - public class InstallFile + public partial class InstallFile { private static readonly Regex FileTypeMatchRegex = new Regex(Util.REGEX_Version + ".txt", RegexOptions.Compiled); @@ -84,7 +86,7 @@ public InstallFile(string fileName, string filePath) this.Path = filePath; } - [Obsolete("Deprecated in 9.11.0, will be removed in 11.0.0, replaced with .net compression types.")] + [Obsolete("Deprecated in DotNetNuke 9.11.0. Replaced with .NET compresstion types. Scheduled for removal in v11.0.0.")] public InstallFile(ZipInputStream zip, ZipEntry entry, InstallerInfo info) { this.Encoding = TextEncoding.UTF8; @@ -278,8 +280,8 @@ private void ReadZip(ZipArchiveEntry entry) File.SetLastWriteTime(this.TempFileName, entry.LastWriteTime.LocalDateTime); } - [Obsolete("Deprecated in 9.11.0, will be removed in 11.0.0.")] - private void ReadZip(ZipInputStream unzip, ZipEntry entry) + [DnnDeprecated(9, 11, 0, "No replacement")] + private partial void ReadZip(ZipInputStream unzip, ZipEntry entry) { this.ParseFileName(entry.Name); Util.WriteStream(unzip, this.TempFileName); diff --git a/DNN Platform/Library/Services/Installer/Installers/ScriptInstaller.cs b/DNN Platform/Library/Services/Installer/Installers/ScriptInstaller.cs index cce31f5e8c1..edcd533266a 100644 --- a/DNN Platform/Library/Services/Installer/Installers/ScriptInstaller.cs +++ b/DNN Platform/Library/Services/Installer/Installers/ScriptInstaller.cs @@ -93,7 +93,7 @@ protected IList PreUpgradeScripts } } - [Obsolete("This is now the first of the PostUpgrade scripts. Will be removed in DNN 11.0.")] + [Obsolete("Deprecated in DotNetNuke 9.9.0. This is now the first of the PostUpgrade scripts. Scheduled for removal in v11.0.0.")] protected InstallFile UpgradeScript => this.PostUpgradeScripts[0]; /// Gets a list of Post-Upgrade Scripts (if present) - these scripts will always run after and versioned upgrade scripts and also after initial install. diff --git a/DNN Platform/Library/Services/Installer/LegacyUtil.cs b/DNN Platform/Library/Services/Installer/LegacyUtil.cs index 6aaab4a7418..5662a17fb5c 100644 --- a/DNN Platform/Library/Services/Installer/LegacyUtil.cs +++ b/DNN Platform/Library/Services/Installer/LegacyUtil.cs @@ -1,388 +1,390 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information -namespace DotNetNuke.Services.Installer -{ - using System; - using System.IO; - using System.Text; - using System.Xml; - using System.Xml.XPath; - - using DotNetNuke.Common; - using DotNetNuke.Common.Utilities; - using DotNetNuke.Entities.Controllers; - using DotNetNuke.Entities.Modules; - using DotNetNuke.Entities.Portals; - using DotNetNuke.Instrumentation; - using DotNetNuke.Services.Installer.Packages; - using DotNetNuke.Services.Installer.Writers; - using DotNetNuke.Services.Localization; +namespace DotNetNuke.Services.Installer +{ + using System; + using System.IO; + using System.Text; + using System.Xml; + using System.Xml.XPath; + + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Controllers; + using DotNetNuke.Entities.Modules; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Instrumentation; + using DotNetNuke.Internal.SourceGenerators; + using DotNetNuke.Services.Installer.Packages; + using DotNetNuke.Services.Installer.Writers; + using DotNetNuke.Services.Localization; using DotNetNuke.UI.Skins; + using Newtonsoft.Json; + + /// + /// The LegacyUtil class is a Utility class that provides helper methods to transfer + /// legacy packages to Cambrian's Universal Installer based system. + /// + public partial class LegacyUtil + { + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(LegacyUtil)); + + private static string adminModules = + "Adsense, MarketShare, Authentication, Banners, FeedExplorer, FileManager, HostSettings, Lists, LogViewer, Newsletters, PortalAliases, Portals, RecycleBin, Scheduler, SearchAdmin, SearchInput, SearchResults, Security, SiteLog, SiteWizard, SQL, Tabs, Vendors,"; + + private static string coreModules = + "DNN_Announcements, Blog, DNN_Documents, DNN_Events, DNN_FAQs, DNN_Feedback, DNN_Forum, Help, DNN_HTML, DNN_IFrame, DNN_Links, DNN_Media, DNN_NewsFeeds, DNN_Reports, Repository, Repository Dashboard, Store Admin, Store Account, Store Catalog, Store Mini Cart, Store Menu, DNN_Survey, DNN_UserDefinedTable, DNN_UsersOnline, Wiki, DNN_XML,"; + + private static string knownSkinObjects = + "ACTIONBUTTON, ACTIONS, BANNER, BREADCRUMB, COPYRIGHT, CURRENTDATE, DOTNETNUKE, DROPDOWNACTIONS, HELP, HOSTNAME, ICON, LANGUAGE, LINKACTIONS, LINKS, LOGIN, LOGO, MENU, NAV, PRINTMODULE, PRIVACY, SEARCH, SIGNIN, STYLES, TERMS, TEXT, TITLE, TREEVIEW, USER, VISIBILITY,"; + + private static string knownSkins = "DNN-Blue, DNN-Gray, MinimalExtropy,"; + + public static string CreateSkinManifest(string skinFolder, string skinType, string tempInstallFolder) + { + // Test if there are Skins and Containers folders in TempInstallFolder (ie it is a legacy combi package) + bool isCombi = false; + var installFolder = new DirectoryInfo(tempInstallFolder); + DirectoryInfo[] subFolders = installFolder.GetDirectories(); + if (subFolders.Length > 0) + { + if (subFolders[0].Name.Equals("containers", StringComparison.InvariantCultureIgnoreCase) || subFolders[0].Name.Equals("skins", StringComparison.InvariantCultureIgnoreCase)) + { + isCombi = true; + } + } + + // Create a writer to create the processed manifest + var sb = new StringBuilder(); + using (XmlWriter writer = XmlWriter.Create(sb, XmlUtils.GetXmlWriterSettings(ConformanceLevel.Fragment))) + { + PackageWriterBase.WriteManifestStartElement(writer); + if (isCombi) + { + if (Directory.Exists(Path.Combine(tempInstallFolder, "Skins"))) + { + // Add Skin Package Fragment + CreateSkinManifest(writer, skinFolder, "Skin", tempInstallFolder.Replace(Globals.ApplicationMapPath + "\\", string.Empty), "Skins"); + } + + if (Directory.Exists(Path.Combine(tempInstallFolder, "Containers"))) + { + // Add Container PAckage Fragment + CreateSkinManifest(writer, skinFolder, "Container", tempInstallFolder.Replace(Globals.ApplicationMapPath + "\\", string.Empty), "Containers"); + } + } + else + { + // Add Package Fragment + CreateSkinManifest(writer, skinFolder, skinType, tempInstallFolder.Replace(Globals.ApplicationMapPath + "\\", string.Empty), string.Empty); + } + + PackageWriterBase.WriteManifestEndElement(writer); + + // Close XmlWriter + writer.Close(); + + // Return new manifest + return sb.ToString(); + } + } + + public static void ParsePackageName(PackageInfo package) + { + ParsePackageName(package, "."); + if (string.IsNullOrEmpty(package.Owner)) + { + ParsePackageName(package, "\\"); + } + + if (string.IsNullOrEmpty(package.Owner)) + { + ParsePackageName(package, "_"); + } + + if ((package.PackageType.Equals("Module", StringComparison.OrdinalIgnoreCase) && adminModules.Contains(package.Name + ",")) || (package.PackageType.Equals("Module", StringComparison.OrdinalIgnoreCase) && coreModules.Contains(package.Name + ",")) || ((package.PackageType.Equals("Container", StringComparison.OrdinalIgnoreCase) || package.PackageType.Equals("Skin", StringComparison.OrdinalIgnoreCase)) && knownSkins.Contains(package.Name + ",")) || (package.PackageType.Equals("SkinObject", StringComparison.OrdinalIgnoreCase) && knownSkinObjects.Contains(package.Name + ","))) + { + if (string.IsNullOrEmpty(package.Owner)) + { + package.Owner = "DotNetNuke"; + package.Name = "DotNetNuke." + package.Name; + switch (package.PackageType) + { + case "Skin": + package.Name += ".Skin"; + package.FriendlyName += " Skin"; + break; + case "Container": + package.Name += ".Container"; + package.FriendlyName += " Container"; + break; + case "SkinObject": + package.Name += "SkinObject"; + package.FriendlyName += " SkinObject"; + break; + } + } + } + + if (package.Owner == "DotNetNuke" || package.Owner == "DNN") + { + package.License = Localization.GetString("License", Localization.GlobalResourceFile); + package.Organization = ".NET Foundation"; + package.Url = "https://dnncommunity.org"; + package.Email = "info@dnncommunity.org"; + package.ReleaseNotes = "There are no release notes for this version."; + } + else + { + package.License = Util.PACKAGE_NoLicense; + } + } + + /// Process legacy language package (that is based on manifest xml file). + [DnnDeprecated(9, 8, 0, "Module package required, functionality removed", RemovalVersion = 10)] + public static partial void ProcessLegacyLanguages() + { + string filePath = Globals.ApplicationMapPath + Localization.SupportedLocalesFile.Substring(1).Replace("/", "\\"); + if (File.Exists(filePath)) + { + var doc = new XPathDocument(filePath); + + // Check for Browser and Url settings + XPathNavigator browserNav = doc.CreateNavigator().SelectSingleNode("root/browserDetection"); + if (browserNav != null) + { + HostController.Instance.Update("EnableBrowserLanguage", Util.ReadAttribute(browserNav, "enabled", false, null, Null.NullString, "true")); + } + + XPathNavigator urlNav = doc.CreateNavigator().SelectSingleNode("root/languageInUrl"); + if (urlNav != null) + { + HostController.Instance.Update("EnableUrlLanguage", Util.ReadAttribute(urlNav, "enabled", false, null, Null.NullString, "true")); + } + + // Process each language + foreach (XPathNavigator nav in doc.CreateNavigator().Select("root/language")) + { + if (nav.NodeType != XPathNodeType.Comment) + { + var language = new Locale(); + language.Text = Util.ReadAttribute(nav, "name"); + language.Code = Util.ReadAttribute(nav, "key"); + language.Fallback = Util.ReadAttribute(nav, "fallback"); + + // Save Language + Localization.SaveLanguage(language); + if (language.Code != Localization.SystemLocale) + { + // Create a Package + var package = new PackageInfo(new InstallerInfo()) + { + Name = language.Text, + FriendlyName = language.Text, + Description = Null.NullString, + Version = new Version(1, 0, 0), + PackageType = "CoreLanguagePack", + License = Util.PACKAGE_NoLicense, + }; + + // Create a LanguagePackWriter + var packageWriter = new LanguagePackWriter(language, package); + + // Save the manifest + package.Manifest = packageWriter.WriteManifest(true); + + // Save Package + PackageController.Instance.SaveExtensionPackage(package); + + var languagePack = new LanguagePackInfo + { + LanguageID = language.LanguageId, + PackageID = package.PackageID, + DependentPackageID = -2, + }; + LanguagePackController.SaveLanguagePack(languagePack); + } + } + } + } + + // Process Portal Locales files + foreach (PortalInfo portal in PortalController.Instance.GetPortals()) + { + int portalID = portal.PortalID; + filePath = string.Format(Globals.ApplicationMapPath + Localization.ApplicationResourceDirectory.Substring(1).Replace("/", "\\") + "\\Locales.Portal-{0}.xml", portalID); - /// - /// The LegacyUtil class is a Utility class that provides helper methods to transfer - /// legacy packages to Cambrian's Universal Installer based system. - /// - public class LegacyUtil - { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(LegacyUtil)); - - private static string adminModules = - "Adsense, MarketShare, Authentication, Banners, FeedExplorer, FileManager, HostSettings, Lists, LogViewer, Newsletters, PortalAliases, Portals, RecycleBin, Scheduler, SearchAdmin, SearchInput, SearchResults, Security, SiteLog, SiteWizard, SQL, Tabs, Vendors,"; - - private static string coreModules = - "DNN_Announcements, Blog, DNN_Documents, DNN_Events, DNN_FAQs, DNN_Feedback, DNN_Forum, Help, DNN_HTML, DNN_IFrame, DNN_Links, DNN_Media, DNN_NewsFeeds, DNN_Reports, Repository, Repository Dashboard, Store Admin, Store Account, Store Catalog, Store Mini Cart, Store Menu, DNN_Survey, DNN_UserDefinedTable, DNN_UsersOnline, Wiki, DNN_XML,"; - - private static string knownSkinObjects = - "ACTIONBUTTON, ACTIONS, BANNER, BREADCRUMB, COPYRIGHT, CURRENTDATE, DOTNETNUKE, DROPDOWNACTIONS, HELP, HOSTNAME, ICON, LANGUAGE, LINKACTIONS, LINKS, LOGIN, LOGO, MENU, NAV, PRINTMODULE, PRIVACY, SEARCH, SIGNIN, STYLES, TERMS, TEXT, TITLE, TREEVIEW, USER, VISIBILITY,"; - - private static string knownSkins = "DNN-Blue, DNN-Gray, MinimalExtropy,"; - - public static string CreateSkinManifest(string skinFolder, string skinType, string tempInstallFolder) - { - // Test if there are Skins and Containers folders in TempInstallFolder (ie it is a legacy combi package) - bool isCombi = false; - var installFolder = new DirectoryInfo(tempInstallFolder); - DirectoryInfo[] subFolders = installFolder.GetDirectories(); - if (subFolders.Length > 0) - { - if (subFolders[0].Name.Equals("containers", StringComparison.InvariantCultureIgnoreCase) || subFolders[0].Name.Equals("skins", StringComparison.InvariantCultureIgnoreCase)) - { - isCombi = true; - } - } - - // Create a writer to create the processed manifest - var sb = new StringBuilder(); - using (XmlWriter writer = XmlWriter.Create(sb, XmlUtils.GetXmlWriterSettings(ConformanceLevel.Fragment))) - { - PackageWriterBase.WriteManifestStartElement(writer); - if (isCombi) - { - if (Directory.Exists(Path.Combine(tempInstallFolder, "Skins"))) - { - // Add Skin Package Fragment - CreateSkinManifest(writer, skinFolder, "Skin", tempInstallFolder.Replace(Globals.ApplicationMapPath + "\\", string.Empty), "Skins"); - } - - if (Directory.Exists(Path.Combine(tempInstallFolder, "Containers"))) - { - // Add Container PAckage Fragment - CreateSkinManifest(writer, skinFolder, "Container", tempInstallFolder.Replace(Globals.ApplicationMapPath + "\\", string.Empty), "Containers"); - } - } - else - { - // Add Package Fragment - CreateSkinManifest(writer, skinFolder, skinType, tempInstallFolder.Replace(Globals.ApplicationMapPath + "\\", string.Empty), string.Empty); - } - - PackageWriterBase.WriteManifestEndElement(writer); - - // Close XmlWriter - writer.Close(); - - // Return new manifest - return sb.ToString(); - } - } - - public static void ParsePackageName(PackageInfo package) - { - ParsePackageName(package, "."); - if (string.IsNullOrEmpty(package.Owner)) - { - ParsePackageName(package, "\\"); - } - - if (string.IsNullOrEmpty(package.Owner)) - { - ParsePackageName(package, "_"); - } - - if ((package.PackageType.Equals("Module", StringComparison.OrdinalIgnoreCase) && adminModules.Contains(package.Name + ",")) || (package.PackageType.Equals("Module", StringComparison.OrdinalIgnoreCase) && coreModules.Contains(package.Name + ",")) || ((package.PackageType.Equals("Container", StringComparison.OrdinalIgnoreCase) || package.PackageType.Equals("Skin", StringComparison.OrdinalIgnoreCase)) && knownSkins.Contains(package.Name + ",")) || (package.PackageType.Equals("SkinObject", StringComparison.OrdinalIgnoreCase) && knownSkinObjects.Contains(package.Name + ","))) - { - if (string.IsNullOrEmpty(package.Owner)) - { - package.Owner = "DotNetNuke"; - package.Name = "DotNetNuke." + package.Name; - switch (package.PackageType) - { - case "Skin": - package.Name += ".Skin"; - package.FriendlyName += " Skin"; - break; - case "Container": - package.Name += ".Container"; - package.FriendlyName += " Container"; - break; - case "SkinObject": - package.Name += "SkinObject"; - package.FriendlyName += " SkinObject"; - break; - } - } - } - - if (package.Owner == "DotNetNuke" || package.Owner == "DNN") - { - package.License = Localization.GetString("License", Localization.GlobalResourceFile); - package.Organization = ".NET Foundation"; - package.Url = "https://dnncommunity.org"; - package.Email = "info@dnncommunity.org"; - package.ReleaseNotes = "There are no release notes for this version."; - } - else - { - package.License = Util.PACKAGE_NoLicense; - } - } - - /// Process legacy language package (that is based on manifest xml file). - [Obsolete("Module package required, functionality removed. Will be removed in 10.0.0.")] - public static void ProcessLegacyLanguages() - { - string filePath = Globals.ApplicationMapPath + Localization.SupportedLocalesFile.Substring(1).Replace("/", "\\"); - if (File.Exists(filePath)) - { - var doc = new XPathDocument(filePath); - - // Check for Browser and Url settings - XPathNavigator browserNav = doc.CreateNavigator().SelectSingleNode("root/browserDetection"); - if (browserNav != null) - { - HostController.Instance.Update("EnableBrowserLanguage", Util.ReadAttribute(browserNav, "enabled", false, null, Null.NullString, "true")); - } - - XPathNavigator urlNav = doc.CreateNavigator().SelectSingleNode("root/languageInUrl"); - if (urlNav != null) - { - HostController.Instance.Update("EnableUrlLanguage", Util.ReadAttribute(urlNav, "enabled", false, null, Null.NullString, "true")); - } - - // Process each language - foreach (XPathNavigator nav in doc.CreateNavigator().Select("root/language")) - { - if (nav.NodeType != XPathNodeType.Comment) - { - var language = new Locale(); - language.Text = Util.ReadAttribute(nav, "name"); - language.Code = Util.ReadAttribute(nav, "key"); - language.Fallback = Util.ReadAttribute(nav, "fallback"); - - // Save Language - Localization.SaveLanguage(language); - if (language.Code != Localization.SystemLocale) - { - // Create a Package - var package = new PackageInfo(new InstallerInfo()) - { - Name = language.Text, - FriendlyName = language.Text, - Description = Null.NullString, - Version = new Version(1, 0, 0), - PackageType = "CoreLanguagePack", - License = Util.PACKAGE_NoLicense, - }; - - // Create a LanguagePackWriter - var packageWriter = new LanguagePackWriter(language, package); - - // Save the manifest - package.Manifest = packageWriter.WriteManifest(true); - - // Save Package - PackageController.Instance.SaveExtensionPackage(package); - - var languagePack = new LanguagePackInfo - { - LanguageID = language.LanguageId, - PackageID = package.PackageID, - DependentPackageID = -2, - }; - LanguagePackController.SaveLanguagePack(languagePack); - } - } - } - } - - // Process Portal Locales files - foreach (PortalInfo portal in PortalController.Instance.GetPortals()) - { - int portalID = portal.PortalID; - filePath = string.Format(Globals.ApplicationMapPath + Localization.ApplicationResourceDirectory.Substring(1).Replace("/", "\\") + "\\Locales.Portal-{0}.xml", portalID); - - if (File.Exists(filePath)) - { - var doc = new XPathDocument(filePath); - - // Check for Browser and Url settings - XPathNavigator browserNav = doc.CreateNavigator().SelectSingleNode("locales/browserDetection"); - if (browserNav != null) - { - PortalController.UpdatePortalSetting(portalID, "EnableBrowserLanguage", Util.ReadAttribute(browserNav, "enabled", false, null, Null.NullString, "true")); - } - - XPathNavigator urlNav = doc.CreateNavigator().SelectSingleNode("locales/languageInUrl"); - if (urlNav != null) - { - PortalController.UpdatePortalSetting(portalID, "EnableUrlLanguage", Util.ReadAttribute(urlNav, "enabled", false, null, Null.NullString, "true")); - } - - foreach (Locale installedLanguage in LocaleController.Instance.GetLocales(Null.NullInteger).Values) - { - string code = installedLanguage.Code; - bool bFound = false; - - // Check if this language is "inactive" - foreach (XPathNavigator inactiveNav in doc.CreateNavigator().Select("locales/inactive/locale")) - { - if (inactiveNav.Value == code) - { - bFound = true; - break; - } - } - - if (!bFound) - { - // Language is enabled - add to portal - Localization.AddLanguageToPortal(portalID, installedLanguage.LanguageId, false); - } - } - } - else - { - foreach (Locale installedLanguage in LocaleController.Instance.GetLocales(Null.NullInteger).Values) - { - // Language is enabled - add to portal - Localization.AddLanguageToPortal(portalID, installedLanguage.LanguageId, false); - } - } - } + if (File.Exists(filePath)) + { + var doc = new XPathDocument(filePath); + + // Check for Browser and Url settings + XPathNavigator browserNav = doc.CreateNavigator().SelectSingleNode("locales/browserDetection"); + if (browserNav != null) + { + PortalController.UpdatePortalSetting(portalID, "EnableBrowserLanguage", Util.ReadAttribute(browserNav, "enabled", false, null, Null.NullString, "true")); + } + + XPathNavigator urlNav = doc.CreateNavigator().SelectSingleNode("locales/languageInUrl"); + if (urlNav != null) + { + PortalController.UpdatePortalSetting(portalID, "EnableUrlLanguage", Util.ReadAttribute(urlNav, "enabled", false, null, Null.NullString, "true")); + } + + foreach (Locale installedLanguage in LocaleController.Instance.GetLocales(Null.NullInteger).Values) + { + string code = installedLanguage.Code; + bool bFound = false; + + // Check if this language is "inactive" + foreach (XPathNavigator inactiveNav in doc.CreateNavigator().Select("locales/inactive/locale")) + { + if (inactiveNav.Value == code) + { + bFound = true; + break; + } + } + + if (!bFound) + { + // Language is enabled - add to portal + Localization.AddLanguageToPortal(portalID, installedLanguage.LanguageId, false); + } + } + } + else + { + foreach (Locale installedLanguage in LocaleController.Instance.GetLocales(Null.NullInteger).Values) + { + // Language is enabled - add to portal + Localization.AddLanguageToPortal(portalID, installedLanguage.LanguageId, false); + } + } + } + } + + /// Process legacy module version 3 .dnn install file. + /// + [DnnDeprecated(9, 8, 0, "Version 3 package formats not supported, must use modern package format", RemovalVersion = 10)] + public static partial void ProcessLegacyModule(DesktopModuleInfo desktopModule) + { + // Get the Module folder + string moduleFolder = Path.Combine(Globals.ApplicationMapPath, Path.Combine("DesktopModules", desktopModule.FolderName)); + + // Find legacy manifest + XPathNavigator rootNav = null; + try + { + string hostModules = "Portals, SQL, HostSettings, Scheduler, SearchAdmin, Lists, SkinDesigner, Extensions"; + string[] files = Directory.GetFiles(moduleFolder, "*.dnn.config"); + if (files.Length > 0) + { + // Create an XPathDocument from the Xml + var doc = new XPathDocument(new FileStream(files[0], FileMode.Open, FileAccess.Read)); + rootNav = doc.CreateNavigator().SelectSingleNode("dotnetnuke"); + } + + // Module is not affiliated with a Package + var package = new PackageInfo(new InstallerInfo()); + package.Name = desktopModule.ModuleName; + + package.FriendlyName = desktopModule.FriendlyName; + package.Description = desktopModule.Description; + package.Version = new Version(1, 0, 0); + if (!string.IsNullOrEmpty(desktopModule.Version)) + { + package.Version = new Version(desktopModule.Version); + } + + if (hostModules.Contains(desktopModule.ModuleName)) + { + // Host Module so make this a system package + package.IsSystemPackage = true; + desktopModule.IsAdmin = true; + } + else + { + desktopModule.IsAdmin = false; + } + + package.PackageType = "Module"; + + // See if the Module is using a "Namespace" for its name + ParsePackageName(package); + + if (files.Length > 0) + { + var modulewriter = new ModulePackageWriter(desktopModule, rootNav, package); + package.Manifest = modulewriter.WriteManifest(true); + } + else + { + package.Manifest = string.Empty; // module has no manifest + } + + // Save Package + PackageController.Instance.SaveExtensionPackage(package); + + // Update Desktop Module with new PackageID + desktopModule.PackageID = package.PackageID; + + // Save DesktopModule + DesktopModuleController.SaveDesktopModule(desktopModule, false, false); + } + catch (Exception exc) + { + Logger.Error(exc); + } + } + + private static PackageInfo CreateSkinPackage(SkinPackageInfo skin) + { + // Create a Package + var package = new PackageInfo(new InstallerInfo()); + package.Name = skin.SkinName; + package.FriendlyName = skin.SkinName; + package.Description = Null.NullString; + package.Version = new Version(1, 0, 0); + package.PackageType = skin.SkinType; + package.License = Util.PACKAGE_NoLicense; + + // See if the Skin is using a Namespace (or is a known skin) + ParsePackageName(package); + + return package; } - /// Process legacy module version 3 .dnn install file. - /// - [Obsolete("Version 3 package formats not supported, must use modern package format. Will be removed in 10.0.0.")] - public static void ProcessLegacyModule(DesktopModuleInfo desktopModule) - { - // Get the Module folder - string moduleFolder = Path.Combine(Globals.ApplicationMapPath, Path.Combine("DesktopModules", desktopModule.FolderName)); - - // Find legacy manifest - XPathNavigator rootNav = null; - try - { - string hostModules = "Portals, SQL, HostSettings, Scheduler, SearchAdmin, Lists, SkinDesigner, Extensions"; - string[] files = Directory.GetFiles(moduleFolder, "*.dnn.config"); - if (files.Length > 0) - { - // Create an XPathDocument from the Xml - var doc = new XPathDocument(new FileStream(files[0], FileMode.Open, FileAccess.Read)); - rootNav = doc.CreateNavigator().SelectSingleNode("dotnetnuke"); - } - - // Module is not affiliated with a Package - var package = new PackageInfo(new InstallerInfo()); - package.Name = desktopModule.ModuleName; - - package.FriendlyName = desktopModule.FriendlyName; - package.Description = desktopModule.Description; - package.Version = new Version(1, 0, 0); - if (!string.IsNullOrEmpty(desktopModule.Version)) - { - package.Version = new Version(desktopModule.Version); - } - - if (hostModules.Contains(desktopModule.ModuleName)) - { - // Host Module so make this a system package - package.IsSystemPackage = true; - desktopModule.IsAdmin = true; - } - else - { - desktopModule.IsAdmin = false; - } - - package.PackageType = "Module"; - - // See if the Module is using a "Namespace" for its name - ParsePackageName(package); - - if (files.Length > 0) - { - var modulewriter = new ModulePackageWriter(desktopModule, rootNav, package); - package.Manifest = modulewriter.WriteManifest(true); - } - else - { - package.Manifest = string.Empty; // module has no manifest - } - - // Save Package - PackageController.Instance.SaveExtensionPackage(package); - - // Update Desktop Module with new PackageID - desktopModule.PackageID = package.PackageID; - - // Save DesktopModule - DesktopModuleController.SaveDesktopModule(desktopModule, false, false); - } - catch (Exception exc) - { - Logger.Error(exc); - } - } - - private static PackageInfo CreateSkinPackage(SkinPackageInfo skin) - { - // Create a Package - var package = new PackageInfo(new InstallerInfo()); - package.Name = skin.SkinName; - package.FriendlyName = skin.SkinName; - package.Description = Null.NullString; - package.Version = new Version(1, 0, 0); - package.PackageType = skin.SkinType; - package.License = Util.PACKAGE_NoLicense; - - // See if the Skin is using a Namespace (or is a known skin) - ParsePackageName(package); - - return package; - } - - private static void CreateSkinManifest(XmlWriter writer, string skinFolder, string skinType, string tempInstallFolder, string subFolder) - { - string skinName = Path.GetFileNameWithoutExtension(skinFolder); - var skin = new SkinPackageInfo(); - skin.SkinName = skinName; - skin.SkinType = skinType; - - // Create a Package - PackageInfo package = CreateSkinPackage(skin); - - // Create a SkinPackageWriter - var skinWriter = new SkinPackageWriter(skin, package, tempInstallFolder, subFolder); - skinWriter.GetFiles(false); - - // We need to reset the BasePath so it using the correct basePath rather than the Temp InstallFolder - skinWriter.SetBasePath(); - - // Writer package manifest fragment to writer - skinWriter.WriteManifest(writer, true); - } - - private static void ParsePackageName(PackageInfo package, string separator) - { - // See if the Module is using a "Namespace" for its name - int ownerIndex = package.Name.IndexOf(separator); - if (ownerIndex > 0) - { - package.Owner = package.Name.Substring(0, ownerIndex); - } - } - } -} + private static void CreateSkinManifest(XmlWriter writer, string skinFolder, string skinType, string tempInstallFolder, string subFolder) + { + string skinName = Path.GetFileNameWithoutExtension(skinFolder); + var skin = new SkinPackageInfo(); + skin.SkinName = skinName; + skin.SkinType = skinType; + + // Create a Package + PackageInfo package = CreateSkinPackage(skin); + + // Create a SkinPackageWriter + var skinWriter = new SkinPackageWriter(skin, package, tempInstallFolder, subFolder); + skinWriter.GetFiles(false); + + // We need to reset the BasePath so it using the correct basePath rather than the Temp InstallFolder + skinWriter.SetBasePath(); + + // Writer package manifest fragment to writer + skinWriter.WriteManifest(writer, true); + } + + private static void ParsePackageName(PackageInfo package, string separator) + { + // See if the Module is using a "Namespace" for its name + int ownerIndex = package.Name.IndexOf(separator); + if (ownerIndex > 0) + { + package.Owner = package.Name.Substring(0, ownerIndex); + } + } + } +} diff --git a/DNN Platform/Library/Services/Installer/Packages/PackageController.cs b/DNN Platform/Library/Services/Installer/Packages/PackageController.cs index d3e10cb817a..871ed4ebbe7 100644 --- a/DNN Platform/Library/Services/Installer/Packages/PackageController.cs +++ b/DNN Platform/Library/Services/Installer/Packages/PackageController.cs @@ -18,6 +18,7 @@ namespace DotNetNuke.Services.Installer.Packages using DotNetNuke.Entities.Portals; using DotNetNuke.Entities.Users; using DotNetNuke.Framework; + using DotNetNuke.Internal.SourceGenerators; using DotNetNuke.Services.Authentication; using DotNetNuke.Services.Installer.Dependencies; using DotNetNuke.Services.Localization; @@ -25,7 +26,7 @@ namespace DotNetNuke.Services.Installer.Packages using DotNetNuke.UI.Skins; /// The PackageController class provides the business class for the packages. - public class PackageController : ServiceLocator, IPackageController + public partial class PackageController : ServiceLocator, IPackageController { private static readonly DataProvider Provider = DataProvider.Instance(); @@ -259,93 +260,93 @@ public static void ParsePackage(string file, string installPath, Dictionary p.PackageID == packageID)); } - [Obsolete("Deprecated in DNN 7.2, Replaced by GetExtensionPackage(int portalId, Func predicate). Scheduled removal in v10.0.0.")] - public static PackageInfo GetPackage(int packageID) + [DnnDeprecated(7, 2, 0, "Replaced by GetExtensionPackage(int portalId, Func predicate)", RemovalVersion = 10)] + public static partial PackageInfo GetPackage(int packageID) { return Instance.GetExtensionPackage(Null.NullInteger, p => p.PackageID == packageID); } - [Obsolete("Deprecated in DNN 7.2, Replaced by GetExtensionPackage(int portalId, Func predicate). Scheduled removal in v10.0.0.")] - public static PackageInfo GetPackage(int packageID, bool ignoreCache) + [DnnDeprecated(7, 2, 0, "Replaced by GetExtensionPackage(int portalId, Func predicate)", RemovalVersion = 10)] + public static partial PackageInfo GetPackage(int packageID, bool ignoreCache) { return Instance.GetExtensionPackage(Null.NullInteger, p => p.PackageID == packageID); } - [Obsolete("Deprecated in DNN 7.2, Replaced by GetExtensionPackage(int portalId, Func predicate). Scheduled removal in v10.0.0.")] - public static PackageInfo GetPackageByName(string name) + [DnnDeprecated(7, 2, 0, "Replaced by GetExtensionPackage(int portalId, Func predicate)", RemovalVersion = 10)] + public static partial PackageInfo GetPackageByName(string name) { return Instance.GetExtensionPackage(Null.NullInteger, p => p.Name == name); } - [Obsolete("Deprecated in DNN 7.2, Replaced by GetExtensionPackage(int portalId, Func predicate). Scheduled removal in v10.0.0.")] - public static PackageInfo GetPackageByName(int portalId, string name) + [DnnDeprecated(7, 2, 0, "Replaced by GetExtensionPackage(int portalId, Func predicate)", RemovalVersion = 10)] + public static partial PackageInfo GetPackageByName(int portalId, string name) { return Instance.GetExtensionPackage(portalId, p => p.Name == name); } - [Obsolete("Deprecated in DNN 7.2, Replaced by GetExtensionPackages(int portalId, Func predicate). Scheduled removal in v10.0.0.")] - public static List GetPackages() + [DnnDeprecated(7, 2, 0, "Replaced by GetExtensionPackages(int portalId, Func predicate)", RemovalVersion = 10)] + public static partial List GetPackages() { return Instance.GetExtensionPackages(Null.NullInteger).ToList(); } - [Obsolete("Deprecated in DNN 7.2, Replaced by GetExtensionPackages(int portalId, Func predicate). Scheduled removal in v10.0.0.")] - public static List GetPackages(int portalId) + [DnnDeprecated(7, 2, 0, "Replaced by GetExtensionPackages(int portalId, Func predicate)", RemovalVersion = 10)] + public static partial List GetPackages(int portalId) { return Instance.GetExtensionPackages(portalId).ToList(); } - [Obsolete("Deprecated in DNN 7.2, Replaced by GetExtensionPackages(int portalId, Func predicate). Scheduled removal in v10.0.0.")] - public static List GetPackagesByType(string type) + [DnnDeprecated(7, 2, 0, "Replaced by GetExtensionPackages(int portalId, Func predicate)", RemovalVersion = 10)] + public static partial List GetPackagesByType(string type) { return Instance.GetExtensionPackages(Null.NullInteger, p => p.PackageType.Equals(type, StringComparison.OrdinalIgnoreCase)).ToList(); } - [Obsolete("Deprecated in DNN 7.2, Replaced by GetExtensionPackages(int portalId, Func predicate). Scheduled removal in v10.0.0.")] - public static List GetPackagesByType(int portalId, string type) + [DnnDeprecated(7, 2, 0, "Replaced by GetExtensionPackages(int portalId, Func predicate)", RemovalVersion = 10)] + public static partial List GetPackagesByType(int portalId, string type) { return Instance.GetExtensionPackages(portalId, p => p.PackageType.Equals(type, StringComparison.OrdinalIgnoreCase)).ToList(); } - [Obsolete("Deprecated in DNN 7.2, Replaced by GetExtensionPackageType(Func predicate). Scheduled removal in v10.0.0.")] - public static PackageType GetPackageType(string type) + [DnnDeprecated(7, 2, 0, "Replaced by GetExtensionPackageType(Func predicate)", RemovalVersion = 10)] + public static partial PackageType GetPackageType(string type) { return Instance.GetExtensionPackageType(t => t.PackageType == type); } - [Obsolete("Deprecated in DNN 7.2, Replaced by GetExtensionPackageTypes(). Scheduled removal in v10.0.0.")] - public static List GetPackageTypes() + [DnnDeprecated(7, 2, 0, "Replaced by GetExtensionPackageTypes()", RemovalVersion = 10)] + public static partial List GetPackageTypes() { return Instance.GetExtensionPackageTypes().ToList(); } - [Obsolete("Deprecated in DNN 7.2, Replaced by SaveExtensionPackage(PackageInfo package). Scheduled removal in v10.0.0.")] - public static void SavePackage(PackageInfo package) + [DnnDeprecated(7, 2, 0, "Replaced by SaveExtensionPackage(PackageInfo package)", RemovalVersion = 10)] + public static partial void SavePackage(PackageInfo package) { Instance.SaveExtensionPackage(package); } - [Obsolete("Deprecated in DNN 7.2, Replaced by SaveExtensionPackage(PackageInfo package). Scheduled removal in v10.0.0.")] - public static void UpdatePackage(PackageInfo package) + [DnnDeprecated(7, 2, 0, "Replaced by SaveExtensionPackage(PackageInfo package)", RemovalVersion = 10)] + public static partial void UpdatePackage(PackageInfo package) { Instance.SaveExtensionPackage(package); } diff --git a/DNN Platform/Library/Services/Journal/IJournalController.cs b/DNN Platform/Library/Services/Journal/IJournalController.cs index 354b97b566b..05e1697a09f 100644 --- a/DNN Platform/Library/Services/Journal/IJournalController.cs +++ b/DNN Platform/Library/Services/Journal/IJournalController.cs @@ -187,10 +187,10 @@ public interface IJournalController /// User's display name. void LikeComment(int journalId, int commentId, int userId, string displayName); - [Obsolete("Deprecated in DNN 7.2.2. Use SaveJournalItem(JournalItem, ModuleInfo). Scheduled removal in v10.0.0.")] + [Obsolete("Deprecated in DotNetNuke 7.2.2. Use SaveJournalItem(JournalItem, ModuleInfo). Scheduled for removal in v10.0.0.")] void SaveJournalItem(JournalItem journalItem, int tabId); - [Obsolete("Deprecated in DNN 7.2.2. Use UpdateJournalItem(JournalItem, ModuleInfo). Scheduled removal in v10.0.0.")] + [Obsolete("Deprecated in DotNetNuke 7.2.2. Use UpdateJournalItem(JournalItem, ModuleInfo). Scheduled for removal in v10.0.0.")] void UpdateJournalItem(JournalItem journalItem, int tabId); } } diff --git a/DNN Platform/Library/Services/Journal/JournalControllerImpl.cs b/DNN Platform/Library/Services/Journal/JournalControllerImpl.cs index 43d81cb1aeb..4650c718c08 100644 --- a/DNN Platform/Library/Services/Journal/JournalControllerImpl.cs +++ b/DNN Platform/Library/Services/Journal/JournalControllerImpl.cs @@ -18,13 +18,14 @@ namespace DotNetNuke.Services.Journal using DotNetNuke.Entities.Content; using DotNetNuke.Entities.Modules; using DotNetNuke.Entities.Users; + using DotNetNuke.Internal.SourceGenerators; using DotNetNuke.Security; using DotNetNuke.Security.Roles; using DotNetNuke.Services.FileSystem; using DotNetNuke.Services.Search.Entities; using DotNetNuke.Services.Search.Internals; - internal class JournalControllerImpl : IJournalController + internal partial class JournalControllerImpl : IJournalController { private const string AllowResizePhotosSetting = "Journal_AllowResizePhotos"; private const string AllowPhotosSetting = "Journal_AllowPhotos"; @@ -536,16 +537,16 @@ public IEnumerable GetJournalTypes(int portalId) c => CBO.FillCollection(this.dataService.Journal_Types_List(portalId))); } - /// - [Obsolete("Deprecated in DNN 7.2.2. Use SaveJournalItem(JournalItem, ModuleInfo). Scheduled removal in v10.0.0.")] - public void SaveJournalItem(JournalItem journalItem, int tabId) + /// + [DnnDeprecated(7, 2, 2, "Use SaveJournalItem(JournalItem, ModuleInfo)", RemovalVersion = 10)] + public partial void SaveJournalItem(JournalItem journalItem, int tabId) { this.SaveJournalItem(journalItem, tabId, Null.NullInteger); } - /// - [Obsolete("Deprecated in DNN 7.2.2. Use UpdateJournalItem(JournalItem, ModuleInfo). Scheduled removal in v10.0.0.")] - public void UpdateJournalItem(JournalItem journalItem, int tabId) + /// + [DnnDeprecated(7, 2, 2, "Use UpdateJournalItem(JournalItem, ModuleInfo)", RemovalVersion = 10)] + public partial void UpdateJournalItem(JournalItem journalItem, int tabId) { this.UpdateJournalItem(journalItem, tabId, Null.NullInteger); } diff --git a/DNN Platform/Library/Services/Localization/Localization.cs b/DNN Platform/Library/Services/Localization/Localization.cs index 16d5632aba5..48b92417541 100644 --- a/DNN Platform/Library/Services/Localization/Localization.cs +++ b/DNN Platform/Library/Services/Localization/Localization.cs @@ -22,6 +22,7 @@ namespace DotNetNuke.Services.Localization using DotNetNuke.Entities.Tabs; using DotNetNuke.Entities.Users; using DotNetNuke.Instrumentation; + using DotNetNuke.Internal.SourceGenerators; using DotNetNuke.Security.Roles; using DotNetNuke.Services.Localization.Internal; using DotNetNuke.Services.Log.EventLog; @@ -48,7 +49,7 @@ namespace DotNetNuke.Services.Localization /// pageCreationProgressArea.Localization.CurrentFileName = Localization.GetString("Processing", LocalResourceFile); /// /// - public class Localization + public partial class Localization { private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(Localization)); private static string defaultKeyName = "resourcekey"; @@ -546,8 +547,8 @@ public static string GetLocaleName(string code, CultureDropDownTypes displayType /// /// Current PortalSettings. /// A valid CultureInfo. - [Obsolete("Deprecated in Platform 9.8.0. Scheduled removal in v11.0.0. Use overload taking IPortalSettings instead.")] - public static CultureInfo GetPageLocale(PortalSettings portalSettings) + [DnnDeprecated(9, 8, 0, "Use overload taking IPortalSettings instead")] + public static partial CultureInfo GetPageLocale(PortalSettings portalSettings) { return GetPageLocale((IPortalSettings)portalSettings); } @@ -1475,8 +1476,8 @@ public static void SetLanguage(string value) /// This method will configure the Thread culture codes. Any page which does not derive from should /// be sure to call this method in to ensure localization works correctly. See the for an example. /// - [Obsolete("Deprecated in Platform 9.8.0. Scheduled removal in v11.0.0. Use overload taking IPortalSettings instead.")] - public static void SetThreadCultures(CultureInfo cultureInfo, PortalSettings portalSettings) + [DnnDeprecated(9, 8, 0, "Use overload taking IPortalSettings instead")] + public static partial void SetThreadCultures(CultureInfo cultureInfo, PortalSettings portalSettings) { SetThreadCultures(cultureInfo, (IPortalSettings)portalSettings); } diff --git a/DNN Platform/Library/Services/Localization/LocalizationProvider.cs b/DNN Platform/Library/Services/Localization/LocalizationProvider.cs index b53fd12e5b8..174b40bd9c0 100644 --- a/DNN Platform/Library/Services/Localization/LocalizationProvider.cs +++ b/DNN Platform/Library/Services/Localization/LocalizationProvider.cs @@ -211,22 +211,26 @@ private static object GetCompiledResourceFileCallBack(CacheItemArgs cacheItemArg // clone the dictionart so that when merge values into dictionart, it won't // affect the cache data. res = res.ToDictionary(kvp => kvp.Key, kvp => kvp.Value); + res = MergeResourceFile(res, GetResourceFileNameHost(resourceFile, systemLanguage)); res = MergeResourceFile(res, GetResourceFileName(resourceFile, systemLanguage, portalSettings.PortalId)); if (defaultLanguage != systemLanguage) { res = MergeResourceFile(res, GetResourceFileName(resourceFile, defaultLanguage)); + res = MergeResourceFile(res, GetResourceFileNameHost(resourceFile, defaultLanguage)); res = MergeResourceFile(res, GetResourceFileName(resourceFile, defaultLanguage, portalSettings.PortalId)); } if (fallbackLanguage != defaultLanguage) { res = MergeResourceFile(res, GetResourceFileName(resourceFile, fallbackLanguage)); + res = MergeResourceFile(res, GetResourceFileNameHost(resourceFile, fallbackLanguage)); res = MergeResourceFile(res, GetResourceFileName(resourceFile, fallbackLanguage, portalSettings.PortalId)); } if (locale != fallbackLanguage) { res = MergeResourceFile(res, GetResourceFileName(resourceFile, locale)); + res = MergeResourceFile(res, GetResourceFileNameHost(resourceFile, locale)); res = MergeResourceFile(res, GetResourceFileName(resourceFile, locale, portalSettings.PortalId)); } @@ -363,6 +367,14 @@ private static Dictionary GetResourceFile(string resourceFile) true); } + private static string GetResourceFileNameHost(string resourceFileRoot, string language) + { + string resourceFile = GetResourceFileName(resourceFileRoot, language); + resourceFile = resourceFile.Replace(".resx", ".Host.resx"); + + return resourceFile; + } + private static string GetResourceFileName(string resourceFileRoot, string language, int portalId) { string resourceFile = GetResourceFileName(resourceFileRoot, language); diff --git a/DNN Platform/Library/Services/Log/EventLog/IEventLogController.cs b/DNN Platform/Library/Services/Log/EventLog/IEventLogController.cs index 60b26733068..114d84d112a 100644 --- a/DNN Platform/Library/Services/Log/EventLog/IEventLogController.cs +++ b/DNN Platform/Library/Services/Log/EventLog/IEventLogController.cs @@ -1,56 +1,50 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information -namespace DotNetNuke.Services.Log.EventLog -{ - using System; - - using DotNetNuke.Abstractions.Portals; - using DotNetNuke.Entities.Portals; - - /// - /// Do not implement. This interface is only implemented by the DotNetNuke core framework. Outside the framework it should used as a type and for unit test purposes only. - /// There is no guarantee that this interface will not change. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information +namespace DotNetNuke.Services.Log.EventLog +{ + using System; + + using DotNetNuke.Abstractions.Portals; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Internal.SourceGenerators; + + /// + /// Do not implement. This interface is only implemented by the DotNetNuke core framework. Outside the framework it should used as a type and for unit test purposes only. + /// There is no guarantee that this interface will not change. /// - [Obsolete("Deprecated in v9.8.1, use dependency injection to resolve IEventLogger, IEventLogService or IEventLogConfigService instead, scheduled removal in v11.")] - public interface IEventLogController : ILogController + [DnnDeprecated(9, 8, 1, "Use dependency injection to resolve IEventLogger, IEventLogService or IEventLogConfigService instead")] + public partial interface IEventLogController : ILogController { - [Obsolete("Deprecated in v9.8.1, use dependency injection to resolve IEventLogger, IEventLogService or IEventLogConfigService instead, scheduled removal in v11.")] #pragma warning disable SA1600 // Elements should be documented, not documenting since the whole class is deprecated. void AddLog(string propertyName, string propertyValue, EventLogController.EventLogType logType); - [Obsolete("Deprecated in DNN 9.7. It has been replaced by the overload taking IPortalSettings. Scheduled removal in v11.0.0.")] - void AddLog(string propertyName, string propertyValue, PortalSettings portalSettings, int userID, EventLogController.EventLogType logType); - - [Obsolete("Deprecated in DNN 9.7. It has been replaced by the overload taking IPortalSettings. Scheduled removal in v11.0.0.")] - void AddLog(string propertyName, string propertyValue, PortalSettings portalSettings, int userID, string logType); - - [Obsolete("Deprecated in v9.8.1, use dependency injection to resolve IEventLogger, IEventLogService or IEventLogConfigService instead, scheduled removal in v11.")] - void AddLog(string propertyName, string propertyValue, IPortalSettings portalSettings, int userID, EventLogController.EventLogType logType); - - [Obsolete("Deprecated in v9.8.1, use dependency injection to resolve IEventLogger, IEventLogService or IEventLogConfigService instead, scheduled removal in v11.")] - void AddLog(string propertyName, string propertyValue, IPortalSettings portalSettings, int userID, string logType); - - [Obsolete("Deprecated in v9.8.1, use dependency injection to resolve IEventLogger, IEventLogService or IEventLogConfigService instead, scheduled removal in v11.")] - void AddLog(PortalSettings portalSettings, int userID, EventLogController.EventLogType logType); - - [Obsolete("Deprecated in DNN 9.7. It has been replaced by the overload taking IPortalSettings. Scheduled removal in v11.0.0.")] - void AddLog(LogProperties properties, PortalSettings portalSettings, int userID, string logTypeKey, bool bypassBuffering); - - [Obsolete("Deprecated in DNN 9.7. It has been replaced by the overload taking IPortalSettings. Scheduled removal in v11.0.0.")] - void AddLog(object businessObject, PortalSettings portalSettings, int userID, string userName, EventLogController.EventLogType logType); - - [Obsolete("Deprecated in DNN 9.7. It has been replaced by the overload taking IPortalSettings. Scheduled removal in v11.0.0.")] - void AddLog(object businessObject, PortalSettings portalSettings, int userID, string userName, string logType); - - [Obsolete("Deprecated in v9.8.1, use dependency injection to resolve IEventLogger, IEventLogService or IEventLogConfigService instead, scheduled removal in v11.")] - void AddLog(LogProperties properties, IPortalSettings portalSettings, int userID, string logTypeKey, bool bypassBuffering); - - [Obsolete("Deprecated in v9.8.1, use dependency injection to resolve IEventLogger, IEventLogService or IEventLogConfigService instead, scheduled removal in v11.")] - void AddLog(object businessObject, IPortalSettings portalSettings, int userID, string userName, EventLogController.EventLogType logType); - - [Obsolete("Deprecated in v9.8.1, use dependency injection to resolve IEventLogger, IEventLogService or IEventLogConfigService instead, scheduled removal in v11.")] - void AddLog(object businessObject, IPortalSettings portalSettings, int userID, string userName, string logType); + [Obsolete("Deprecated in DotNetNuke 9.7.0. It has been replaced by the overload taking IPortalSettings. Scheduled for removal in v11.0.0.")] + void AddLog(string propertyName, string propertyValue, PortalSettings portalSettings, int userID, EventLogController.EventLogType logType); + + [Obsolete("Deprecated in DotNetNuke 9.7.0. It has been replaced by the overload taking IPortalSettings. Scheduled for removal in v11.0.0.")] + void AddLog(string propertyName, string propertyValue, PortalSettings portalSettings, int userID, string logType); + + void AddLog(string propertyName, string propertyValue, IPortalSettings portalSettings, int userID, EventLogController.EventLogType logType); + + void AddLog(string propertyName, string propertyValue, IPortalSettings portalSettings, int userID, string logType); + + void AddLog(PortalSettings portalSettings, int userID, EventLogController.EventLogType logType); + + [Obsolete("Deprecated in DotNetNuke 9.7.0. It has been replaced by the overload taking IPortalSettings. Scheduled for removal in v11.0.0.")] + void AddLog(LogProperties properties, PortalSettings portalSettings, int userID, string logTypeKey, bool bypassBuffering); + + [Obsolete("Deprecated in DotNetNuke 9.7.0. It has been replaced by the overload taking IPortalSettings. Scheduled for removal in v11.0.0.")] + void AddLog(object businessObject, PortalSettings portalSettings, int userID, string userName, EventLogController.EventLogType logType); + + [Obsolete("Deprecated in DotNetNuke 9.7.0. It has been replaced by the overload taking IPortalSettings. Scheduled for removal in v11.0.0.")] + void AddLog(object businessObject, PortalSettings portalSettings, int userID, string userName, string logType); + + void AddLog(LogProperties properties, IPortalSettings portalSettings, int userID, string logTypeKey, bool bypassBuffering); + + void AddLog(object businessObject, IPortalSettings portalSettings, int userID, string userName, EventLogController.EventLogType logType); + + void AddLog(object businessObject, IPortalSettings portalSettings, int userID, string userName, string logType); #pragma warning restore SA1600 // Elements should be documented - } -} + } +} diff --git a/DNN Platform/Library/Services/Log/EventLog/LoggingProvider.cs b/DNN Platform/Library/Services/Log/EventLog/LoggingProvider.cs index 8b2c8b3781b..eb65b486d02 100644 --- a/DNN Platform/Library/Services/Log/EventLog/LoggingProvider.cs +++ b/DNN Platform/Library/Services/Log/EventLog/LoggingProvider.cs @@ -1,78 +1,78 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information -namespace DotNetNuke.Services.Log.EventLog -{ - using System; - using System.Collections; - using System.Collections.Generic; +namespace DotNetNuke.Services.Log.EventLog +{ + using System; + using System.Collections; + using System.Collections.Generic; using DotNetNuke.Abstractions.Logging; using DotNetNuke.ComponentModel; - public abstract class LoggingProvider + public abstract class LoggingProvider { - [Obsolete("Deprecated in 9.8.0. Not suitable replacement, use Dependency Injection to resolve 'DotNetNuke.Abstractions.Logging.IEventLogService.GetLog()' instead. Scheduled for removal in v11.0.0.")] - public enum ReturnType - { - LogInfoObjects = 0, - XML = 1, - } - - // return the provider - public static LoggingProvider Instance() - { - return ComponentFactory.GetComponent(); - } - - public abstract void AddLog(LogInfo logInfo); - - public abstract void AddLogType(string logTypeKey, string logTypeFriendlyName, string logTypeDescription, string logTypeCSSClass, string logTypeOwner); - - public abstract void AddLogTypeConfigInfo(string id, bool loggingIsActive, string logTypeKey, string logTypePortalID, string keepMostRecent, string logFileName, bool emailNotificationIsActive, string threshold, string notificationThresholdTime, string notificationThresholdTimeType, string mailFromAddress, string mailToAddress); - - public abstract void ClearLog(); - - public abstract void DeleteLog(LogInfo logInfo); - - public abstract void DeleteLogType(string logTypeKey); - - public abstract void DeleteLogTypeConfigInfo(string id); - - public virtual List GetLogs(int portalID, string logType, int pageSize, int pageIndex, ref int totalRecords) - { - return new List(); - } - - public abstract ArrayList GetLogTypeConfigInfo(); - - public abstract ArrayList GetLogTypeInfo(); - - public abstract LogTypeConfigInfo GetLogTypeConfigInfoByID(string id); - + [Obsolete("Deprecated in DotNetNuke 9.8.0. Use Dependency Injection to resolve 'DotNetNuke.Abstractions.Logging.IEventLogService.GetLog()' instead. Scheduled for removal in v11.0.0.")] + public enum ReturnType + { + LogInfoObjects = 0, + XML = 1, + } + + // return the provider + public static LoggingProvider Instance() + { + return ComponentFactory.GetComponent(); + } + + public abstract void AddLog(LogInfo logInfo); + + public abstract void AddLogType(string logTypeKey, string logTypeFriendlyName, string logTypeDescription, string logTypeCSSClass, string logTypeOwner); + + public abstract void AddLogTypeConfigInfo(string id, bool loggingIsActive, string logTypeKey, string logTypePortalID, string keepMostRecent, string logFileName, bool emailNotificationIsActive, string threshold, string notificationThresholdTime, string notificationThresholdTimeType, string mailFromAddress, string mailToAddress); + + public abstract void ClearLog(); + + public abstract void DeleteLog(LogInfo logInfo); + + public abstract void DeleteLogType(string logTypeKey); + + public abstract void DeleteLogTypeConfigInfo(string id); + + public virtual List GetLogs(int portalID, string logType, int pageSize, int pageIndex, ref int totalRecords) + { + return new List(); + } + + public abstract ArrayList GetLogTypeConfigInfo(); + + public abstract ArrayList GetLogTypeInfo(); + + public abstract LogTypeConfigInfo GetLogTypeConfigInfoByID(string id); + public abstract object GetSingleLog(LogInfo logInfo, ReturnType returnType); /// Retrieves a single event log via the Log Guid. /// A string reprenstation of the log Guid. /// The . - public abstract ILogInfo GetLog(string logGuid); - - public abstract bool LoggingIsEnabled(string logType, int portalID); - - public abstract void PurgeLogBuffer(); - - public abstract void SendLogNotifications(); - - public abstract bool SupportsEmailNotification(); - - public abstract bool SupportsInternalViewer(); - - public abstract bool SupportsSendToCoreTeam(); - - public abstract bool SupportsSendViaEmail(); - - public abstract void UpdateLogType(string logTypeKey, string logTypeFriendlyName, string logTypeDescription, string logTypeCSSClass, string logTypeOwner); - - public abstract void UpdateLogTypeConfigInfo(string id, bool loggingIsActive, string logTypeKey, string logTypePortalID, string keepMostRecent, string logFileName, bool emailNotificationIsActive, string threshold, string notificationThresholdTime, string notificationThresholdTimeType, string mailFromAddress, string mailToAddress); - } -} + public abstract ILogInfo GetLog(string logGuid); + + public abstract bool LoggingIsEnabled(string logType, int portalID); + + public abstract void PurgeLogBuffer(); + + public abstract void SendLogNotifications(); + + public abstract bool SupportsEmailNotification(); + + public abstract bool SupportsInternalViewer(); + + public abstract bool SupportsSendToCoreTeam(); + + public abstract bool SupportsSendViaEmail(); + + public abstract void UpdateLogType(string logTypeKey, string logTypeFriendlyName, string logTypeDescription, string logTypeCSSClass, string logTypeOwner); + + public abstract void UpdateLogTypeConfigInfo(string id, bool loggingIsActive, string logTypeKey, string logTypePortalID, string keepMostRecent, string logFileName, bool emailNotificationIsActive, string threshold, string notificationThresholdTime, string notificationThresholdTimeType, string mailFromAddress, string mailToAddress); + } +} diff --git a/DNN Platform/Library/Services/Mail/CoreMailProvider.cs b/DNN Platform/Library/Services/Mail/CoreMailProvider.cs index 7d71b865180..d923ba8c128 100644 --- a/DNN Platform/Library/Services/Mail/CoreMailProvider.cs +++ b/DNN Platform/Library/Services/Mail/CoreMailProvider.cs @@ -124,6 +124,7 @@ private static SmtpInfo GetDefaultSmtpInfo(SmtpInfo smtpInfo) Username = Host.SMTPUsername, Password = Host.SMTPPassword, EnableSSL = Host.EnableSMTPSSL, + AuthProvider = Host.SMTPAuthProvider, }; } diff --git a/DNN Platform/Library/Services/Mail/Mail.cs b/DNN Platform/Library/Services/Mail/Mail.cs index f500fe57af3..f904918f520 100644 --- a/DNN Platform/Library/Services/Mail/Mail.cs +++ b/DNN Platform/Library/Services/Mail/Mail.cs @@ -18,11 +18,12 @@ namespace DotNetNuke.Services.Mail using DotNetNuke.Entities.Host; using DotNetNuke.Entities.Portals; using DotNetNuke.Entities.Users; + using DotNetNuke.Internal.SourceGenerators; using DotNetNuke.Services.Tokens; using Localize = DotNetNuke.Services.Localization.Localization; - public class Mail + public partial class Mail { public static string ConvertToText(string sHTML) { @@ -72,8 +73,8 @@ public static void SendEmail(string fromAddress, string senderAddress, string to MailProvider.Instance().SendMail(mailInfo); } - [Obsolete("This method has been deprecated. Please use SendEmail() with ICollection Scheduled removal in v11.0.0.")] - public static string SendEmail(string fromAddress, string senderAddress, string toAddress, string subject, string body, List attachments) + [DnnDeprecated(9, 8, 0, "Please use SendEmail() with ICollection")] + public static partial string SendEmail(string fromAddress, string senderAddress, string toAddress, string subject, string body, List attachments) { var mailInfo = new MailInfo { @@ -311,7 +312,30 @@ public static string SendMail(string mailFrom, string mailTo, string cc, string smtpAuthentication, smtpUsername, smtpPassword, - smtpEnableSSL); + smtpEnableSSL, + Host.SMTPAuthProvider); + } + + public static string SendMail(string mailFrom, string mailTo, string cc, string bcc, MailPriority priority, string subject, MailFormat bodyFormat, Encoding bodyEncoding, string body, string attachment, string smtpServer, string smtpAuthentication, string smtpUsername, string smtpPassword, bool smtpEnableSSL, string authProvider) + { + return SendMail( + mailFrom, + mailTo, + cc, + bcc, + mailFrom, + priority, + subject, + bodyFormat, + bodyEncoding, + body, + attachment.Split('|'), + smtpServer, + smtpAuthentication, + smtpUsername, + smtpPassword, + smtpEnableSSL, + authProvider); } public static string SendMail(string mailFrom, string mailTo, string cc, string bcc, MailPriority priority, string subject, MailFormat bodyFormat, Encoding bodyEncoding, string body, string[] attachments, string smtpServer, string smtpAuthentication, string smtpUsername, string smtpPassword, bool smtpEnableSSL) @@ -332,7 +356,30 @@ public static string SendMail(string mailFrom, string mailTo, string cc, string smtpAuthentication, smtpUsername, smtpPassword, - smtpEnableSSL); + smtpEnableSSL, + Host.SMTPAuthProvider); + } + + public static string SendMail(string mailFrom, string mailTo, string cc, string bcc, MailPriority priority, string subject, MailFormat bodyFormat, Encoding bodyEncoding, string body, string[] attachments, string smtpServer, string smtpAuthentication, string smtpUsername, string smtpPassword, bool smtpEnableSSL, string authProvider) + { + return SendMail( + mailFrom, + mailTo, + cc, + bcc, + mailFrom, + priority, + subject, + bodyFormat, + bodyEncoding, + body, + attachments, + smtpServer, + smtpAuthentication, + smtpUsername, + smtpPassword, + smtpEnableSSL, + authProvider); } /// Sends an email based on params. @@ -393,11 +440,63 @@ public static string SendMail(string mailFrom, string mailTo, string cc, string smtpAuthentication, smtpUsername, smtpPassword, - smtpEnableSSL); + smtpEnableSSL, + Host.SMTPAuthProvider); + } + + public static string SendMail(string mailFrom, string mailTo, string cc, string bcc, string replyTo, MailPriority priority, string subject, MailFormat bodyFormat, Encoding bodyEncoding, string body, string[] attachments, string smtpServer, string smtpAuthentication, string smtpUsername, string smtpPassword, bool smtpEnableSSL, string authProvider) + { + var attachmentList = (from attachment in attachments + where !string.IsNullOrEmpty(attachment) + select new Attachment(attachment)) + .ToList(); + + return SendMail( + mailFrom, + mailTo, + cc, + bcc, + replyTo, + priority, + subject, + bodyFormat, + bodyEncoding, + body, + attachmentList, + smtpServer, + smtpAuthentication, + smtpUsername, + smtpPassword, + smtpEnableSSL, + authProvider); + } + + [DnnDeprecated(9, 8, 0, "Please use SendEmail() with ICollection")] + public static partial string SendMail(string mailFrom, string mailTo, string cc, string bcc, string replyTo, MailPriority priority, string subject, MailFormat bodyFormat, Encoding bodyEncoding, string body, List attachments, string smtpServer, string smtpAuthentication, string smtpUsername, string smtpPassword, bool smtpEnableSSL) + { + return SendMail( + mailFrom, + string.Empty, + mailTo, + cc, + bcc, + replyTo, + priority, + subject, + bodyFormat, + bodyEncoding, + body, + attachments, + smtpServer, + smtpAuthentication, + smtpUsername, + smtpPassword, + smtpEnableSSL, + Host.SMTPAuthProvider); } [Obsolete("This method has been deprecated. Please use SendEmail() with ICollection Scheduled removal in v11.0.0.")] - public static string SendMail(string mailFrom, string mailTo, string cc, string bcc, string replyTo, MailPriority priority, string subject, MailFormat bodyFormat, Encoding bodyEncoding, string body, List attachments, string smtpServer, string smtpAuthentication, string smtpUsername, string smtpPassword, bool smtpEnableSSL) + public static string SendMail(string mailFrom, string mailTo, string cc, string bcc, string replyTo, MailPriority priority, string subject, MailFormat bodyFormat, Encoding bodyEncoding, string body, List attachments, string smtpServer, string smtpAuthentication, string smtpUsername, string smtpPassword, bool smtpEnableSSL, string authProvider) { return SendMail( mailFrom, @@ -416,7 +515,8 @@ public static string SendMail(string mailFrom, string mailTo, string cc, string smtpAuthentication, smtpUsername, smtpPassword, - smtpEnableSSL); + smtpEnableSSL, + authProvider); } public static string SendMail(string mailFrom, string mailTo, string cc, string bcc, string replyTo, MailPriority priority, string subject, MailFormat bodyFormat, Encoding bodyEncoding, string body, ICollection attachments, string smtpServer, string smtpAuthentication, string smtpUsername, string smtpPassword, bool smtpEnableSSL) @@ -438,11 +538,59 @@ public static string SendMail(string mailFrom, string mailTo, string cc, string smtpAuthentication, smtpUsername, smtpPassword, - smtpEnableSSL); + smtpEnableSSL, + Host.SMTPAuthProvider); + } + + public static string SendMail(string mailFrom, string mailTo, string cc, string bcc, string replyTo, MailPriority priority, string subject, MailFormat bodyFormat, Encoding bodyEncoding, string body, ICollection attachments, string smtpServer, string smtpAuthentication, string smtpUsername, string smtpPassword, bool smtpEnableSSL, string authProvider) + { + return SendMail( + mailFrom, + string.Empty, + mailTo, + cc, + bcc, + replyTo, + priority, + subject, + bodyFormat, + bodyEncoding, + body, + attachments, + smtpServer, + smtpAuthentication, + smtpUsername, + smtpPassword, + smtpEnableSSL, + authProvider); + } + + [DnnDeprecated(9, 8, 0, "Please use SendEmail() with ICollection")] + public static partial string SendMail(string mailFrom, string mailSender, string mailTo, string cc, string bcc, string replyTo, MailPriority priority, string subject, MailFormat bodyFormat, Encoding bodyEncoding, string body, List attachments, string smtpServer, string smtpAuthentication, string smtpUsername, string smtpPassword, bool smtpEnableSSL) + { + return SendMail( + mailFrom, + mailSender, + mailTo, + cc, + bcc, + replyTo, + priority, + subject, + bodyFormat, + bodyEncoding, + body, + attachments, + smtpServer, + smtpAuthentication, + smtpUsername, + smtpPassword, + smtpEnableSSL, + Host.SMTPAuthProvider); } [Obsolete("This method has been deprecated. Please use SendEmail() with ICollection Scheduled removal in v11.0.0.")] - public static string SendMail(string mailFrom, string mailSender, string mailTo, string cc, string bcc, string replyTo, MailPriority priority, string subject, MailFormat bodyFormat, Encoding bodyEncoding, string body, List attachments, string smtpServer, string smtpAuthentication, string smtpUsername, string smtpPassword, bool smtpEnableSSL) + public static string SendMail(string mailFrom, string mailSender, string mailTo, string cc, string bcc, string replyTo, MailPriority priority, string subject, MailFormat bodyFormat, Encoding bodyEncoding, string body, List attachments, string smtpServer, string smtpAuthentication, string smtpUsername, string smtpPassword, bool smtpEnableSSL, string authProvider) { var smtpInfo = new SmtpInfo { @@ -451,6 +599,7 @@ public static string SendMail(string mailFrom, string mailSender, string mailTo, Username = smtpUsername, Password = smtpPassword, EnableSSL = smtpEnableSSL, + AuthProvider = authProvider, }; var mailInfo = new MailInfo @@ -478,6 +627,29 @@ public static string SendMail(string mailFrom, string mailSender, string mailTo, } public static string SendMail(string mailFrom, string mailSender, string mailTo, string cc, string bcc, string replyTo, MailPriority priority, string subject, MailFormat bodyFormat, Encoding bodyEncoding, string body, ICollection attachments, string smtpServer, string smtpAuthentication, string smtpUsername, string smtpPassword, bool smtpEnableSSL) + { + return SendMail( + mailFrom, + mailSender, + mailTo, + cc, + bcc, + replyTo, + priority, + subject, + bodyFormat, + bodyEncoding, + body, + attachments, + smtpServer, + smtpAuthentication, + smtpUsername, + smtpPassword, + smtpEnableSSL, + Host.SMTPAuthProvider); + } + + public static string SendMail(string mailFrom, string mailSender, string mailTo, string cc, string bcc, string replyTo, MailPriority priority, string subject, MailFormat bodyFormat, Encoding bodyEncoding, string body, ICollection attachments, string smtpServer, string smtpAuthentication, string smtpUsername, string smtpPassword, bool smtpEnableSSL, string authProvider) { var smtpInfo = new SmtpInfo { @@ -486,6 +658,7 @@ public static string SendMail(string mailFrom, string mailSender, string mailTo, Username = smtpUsername, Password = smtpPassword, EnableSSL = smtpEnableSSL, + AuthProvider = authProvider, }; var mailInfo = new MailInfo diff --git a/DNN Platform/Library/Services/Mail/MailKitMailProvider.cs b/DNN Platform/Library/Services/Mail/MailKitMailProvider.cs index 1c62074a6f8..36e666630e5 100644 --- a/DNN Platform/Library/Services/Mail/MailKitMailProvider.cs +++ b/DNN Platform/Library/Services/Mail/MailKitMailProvider.cs @@ -1,288 +1,365 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information -namespace DotNetNuke.Services.Mail -{ - using System; - using System.Linq; - using System.Text.RegularExpressions; - using System.Threading; - using System.Threading.Tasks; - - using DotNetNuke.Common.Utilities; - using DotNetNuke.Entities.Host; - using DotNetNuke.Entities.Portals; - +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information +namespace DotNetNuke.Services.Mail +{ + using System; + using System.Linq; + using System.Text.RegularExpressions; + using System.Threading; + using System.Threading.Tasks; + + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Host; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Services.Mail.OAuth; + using MailKit.Net.Smtp; using MailKit.Security; - - using MimeKit; - - using Localize = DotNetNuke.Services.Localization.Localization; - - /// A implementation using ). - public class MailKitMailProvider : MailProvider - { + + using Microsoft.Extensions.DependencyInjection; + + using MimeKit; + + using Localize = DotNetNuke.Services.Localization.Localization; + + /// A implementation using ). + public class MailKitMailProvider : MailProvider + { private static readonly Regex SmtpServerRegex = new Regex("^[^:]+(:[0-9]{1,5})?$", RegexOptions.Compiled); - /// - public override string SendMail(MailInfo mailInfo, SmtpInfo smtpInfo = null) - { - try - { - var (host, port, errorMessage) = ParseSmtpServer(ref smtpInfo); - if (errorMessage != null) - { - return errorMessage; - } - - var mailMessage = CreateMailMessage(mailInfo, smtpInfo); - - using (var smtpClient = new SmtpClient()) - { - smtpClient.Connect(host, port, SecureSocketOptions.Auto); - - if (smtpInfo.Authentication == "1" && !string.IsNullOrEmpty(smtpInfo.Username) && !string.IsNullOrEmpty(smtpInfo.Password)) - { - smtpClient.Authenticate(smtpInfo.Username, smtpInfo.Password); - } - - smtpClient.Send(mailMessage); - smtpClient.Disconnect(true); - } - - return string.Empty; - } - catch (Exception exc) - { - return HandleException(exc); - } + private readonly Lazy smtpOAuthController; + + /// Initializes a new instance of the class. + [Obsolete("Deprecated in DotNetNuke 9.13.0. Use overload taking Lazy. Scheduled removal in v11.0.0.")] + public MailKitMailProvider() + : this(null) + { + } + + /// Initializes a new instance of the class. + /// The SMTP OAuth controller. + public MailKitMailProvider(Lazy smtpOAuthController) + { + this.smtpOAuthController = smtpOAuthController ?? Globals.DependencyProvider.GetRequiredService>(); + } + + /// + public override bool SupportsOAuth => true; + + /// + public override string SendMail(MailInfo mailInfo, SmtpInfo smtpInfo = null) + { + try + { + var (host, port, errorMessage) = ParseSmtpServer(ref smtpInfo); + if (errorMessage != null) + { + return errorMessage; + } + + var mailMessage = CreateMailMessage(mailInfo, smtpInfo); + + using (var smtpClient = new SmtpClient()) + { + smtpClient.Connect(host, port, SecureSocketOptions.Auto); + + if (smtpInfo.Authentication == "1" && !string.IsNullOrEmpty(smtpInfo.Username) && !string.IsNullOrEmpty(smtpInfo.Password)) + { + smtpClient.Authenticate(smtpInfo.Username, smtpInfo.Password); + } + + var (provider, portalId) = this.GetOAuthProvider(smtpClient, smtpInfo); + if (provider != null) + { + provider.Authorize(portalId, new OAuthSmtpClient(smtpClient)); + } + + smtpClient.Send(mailMessage); + smtpClient.Disconnect(true); + } + + return string.Empty; + } + catch (Exception exc) + { + return HandleException(exc); + } + } + + /// + public override async Task SendMailAsync(MailInfo mailInfo, SmtpInfo smtpInfo = null, CancellationToken cancellationToken = default(CancellationToken)) + { + var (host, port, errorMessage) = ParseSmtpServer(ref smtpInfo); + if (errorMessage != null) + { + return errorMessage; + } + + var mailMessage = CreateMailMessage(mailInfo, smtpInfo); + + try + { + using (var smtpClient = new SmtpClient()) + { + await smtpClient.ConnectAsync(host, port, SecureSocketOptions.Auto, cancellationToken); + + if (smtpInfo.Authentication == "1" && !string.IsNullOrEmpty(smtpInfo.Username) && !string.IsNullOrEmpty(smtpInfo.Password)) + { + await smtpClient.AuthenticateAsync(smtpInfo.Username, smtpInfo.Password, cancellationToken); + } + + var (provider, portalId) = this.GetOAuthProvider(smtpClient, smtpInfo); + if (provider != null) + { + await provider.AuthorizeAsync(portalId, new OAuthSmtpClient(smtpClient), cancellationToken); + } + + await smtpClient.SendAsync(mailMessage, cancellationToken); + await smtpClient.DisconnectAsync(true, cancellationToken); + } + + return string.Empty; + } + catch (Exception exc) + { + return HandleException(exc); + } + } + + private static (string host, int port, string errorMessage) ParseSmtpServer(ref SmtpInfo smtpInfo) + { + var port = 25; + if (smtpInfo == null || string.IsNullOrEmpty(smtpInfo.Server)) + { + if (string.IsNullOrWhiteSpace(Host.SMTPServer)) + { + return (null, port, "SMTP Server not configured"); + } + + smtpInfo = new SmtpInfo + { + Server = Host.SMTPServer, + Authentication = Host.SMTPAuthentication, + Username = Host.SMTPUsername, + Password = Host.SMTPPassword, + EnableSSL = Host.EnableSMTPSSL, + AuthProvider = Host.SMTPAuthProvider, + }; + } + + if (smtpInfo.Authentication == "2") + { + throw new NotSupportedException("NTLM authentication is not supported by MailKit provider"); + } + + smtpInfo.Server = smtpInfo.Server.Trim(); + if (!SmtpServerRegex.IsMatch(smtpInfo.Server)) + { + return (null, port, Localize.GetString("SMTPConfigurationProblem")); + } + + var smtpHostParts = smtpInfo.Server.Split(':'); + var host = smtpHostParts[0]; + if (smtpHostParts.Length <= 1) + { + return (host, port, null); + } + + // port is guaranteed to be of max 5 digits numeric by the RegEx check + port = int.Parse(smtpHostParts[1]); + if (port < 1 || port > 65535) + { + return (host, port, Localize.GetString("SmtpInvalidPort")); + } + + return (host, port, null); + } + + private static string HandleException(Exception exc) + { + var retValue = Localize.GetString("SMTPConfigurationProblem") + " "; + + // mail configuration problem + if (exc.InnerException != null) + { + retValue += string.Concat(exc.Message, Environment.NewLine, exc.InnerException.Message); + Exceptions.Exceptions.LogException(exc.InnerException); + } + else + { + retValue += exc.Message; + Exceptions.Exceptions.LogException(exc); + } + + return retValue; + } + + 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 = ToMessagePriority(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; + } + + private static MailboxAddress ParseAddressWithDisplayName(string displayName, string address) + { + var mailboxAddress = MailboxAddress.Parse(address); + if (!string.IsNullOrWhiteSpace(displayName)) + { + mailboxAddress.Name = displayName; + } + + return mailboxAddress; } - /// - public override async Task SendMailAsync(MailInfo mailInfo, SmtpInfo smtpInfo = null, CancellationToken cancellationToken = default(CancellationToken)) - { - var (host, port, errorMessage) = ParseSmtpServer(ref smtpInfo); - if (errorMessage != null) - { - return errorMessage; - } - - var mailMessage = CreateMailMessage(mailInfo, smtpInfo); - - try - { - using (var smtpClient = new SmtpClient()) - { - await smtpClient.ConnectAsync(host, port, SecureSocketOptions.Auto, cancellationToken); - - if (smtpInfo.Authentication == "1" && !string.IsNullOrEmpty(smtpInfo.Username) && !string.IsNullOrEmpty(smtpInfo.Password)) - { - await smtpClient.AuthenticateAsync(smtpInfo.Username, smtpInfo.Password, cancellationToken); - } - - await smtpClient.SendAsync(mailMessage, cancellationToken); - await smtpClient.DisconnectAsync(true, cancellationToken); - } - - return string.Empty; - } - catch (Exception exc) - { - return HandleException(exc); - } - } - - private static (string host, int port, string errorMessage) ParseSmtpServer(ref SmtpInfo smtpInfo) - { - var port = 25; - if (smtpInfo == null || string.IsNullOrEmpty(smtpInfo.Server)) - { - if (string.IsNullOrWhiteSpace(Host.SMTPServer)) - { - return (null, port, "SMTP Server not configured"); - } - - smtpInfo = new SmtpInfo - { - Server = Host.SMTPServer, - Authentication = Host.SMTPAuthentication, - Username = Host.SMTPUsername, - Password = Host.SMTPPassword, - EnableSSL = Host.EnableSMTPSSL, - }; - } - - if (smtpInfo.Authentication == "2") - { - throw new NotSupportedException("NTLM authentication is not supported by MailKit provider"); - } - - smtpInfo.Server = smtpInfo.Server.Trim(); - if (!SmtpServerRegex.IsMatch(smtpInfo.Server)) - { - return (null, port, Localize.GetString("SMTPConfigurationProblem")); - } - - var smtpHostParts = smtpInfo.Server.Split(':'); - var host = smtpHostParts[0]; - if (smtpHostParts.Length <= 1) - { - return (host, port, null); - } - - // port is guaranteed to be of max 5 digits numeric by the RegEx check - port = int.Parse(smtpHostParts[1]); - if (port < 1 || port > 65535) - { - return (host, port, Localize.GetString("SmtpInvalidPort")); - } - - return (host, port, null); - } - - private static string HandleException(Exception exc) - { - var retValue = Localize.GetString("SMTPConfigurationProblem") + " "; - - // mail configuration problem - if (exc.InnerException != null) - { - retValue += string.Concat(exc.Message, Environment.NewLine, exc.InnerException.Message); - Exceptions.Exceptions.LogException(exc.InnerException); - } - else - { - retValue += exc.Message; - Exceptions.Exceptions.LogException(exc); - } - - return retValue; - } - - 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 = ToMessagePriority(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; - } - - private static MailboxAddress ParseAddressWithDisplayName(string displayName, string address) - { - var mailboxAddress = MailboxAddress.Parse(address); - if (!string.IsNullOrWhiteSpace(displayName)) - { - mailboxAddress.Name = displayName; - } - - return mailboxAddress; + private static MessagePriority ToMessagePriority(MailPriority priority) + { + switch (priority) + { + case MailPriority.Low: + return MessagePriority.NonUrgent; + case MailPriority.Normal: + return MessagePriority.Normal; + case MailPriority.High: + return MessagePriority.Urgent; + default: + throw new ArgumentException($"Invalid MailPriority value: {priority}", nameof(priority)); + } } - private static MessagePriority ToMessagePriority(MailPriority priority) - { - switch (priority) - { - case MailPriority.Low: - return MessagePriority.NonUrgent; - case MailPriority.Normal: - return MessagePriority.Normal; - case MailPriority.High: - return MessagePriority.Urgent; - default: - throw new ArgumentException($"Invalid MailPriority value: {priority}", nameof(priority)); - } - } - } -} + private (ISmtpOAuthProvider, int) GetOAuthProvider(SmtpClient smtpClient, SmtpInfo smtpInfo) + { + var usingOAuth = smtpInfo.Authentication == "3"; + if (usingOAuth) + { + var authProvider = this.smtpOAuthController.Value.GetOAuthProvider(smtpInfo.AuthProvider); + if (authProvider != null) + { + var portalId = Null.NullInteger; + if (Host.SMTPPortalEnabled) + { + portalId = PortalSettings.Current.PortalId; + } + + return (authProvider, portalId); + } + } + + return (null, Null.NullInteger); + } + + private class OAuthSmtpClient : IOAuth2SmtpClient + { + public OAuthSmtpClient(ISmtpClient smtpClient) + { + this.SmtpClient = smtpClient; + } + + public ISmtpClient SmtpClient { get; } + + public void Authenticate(string username, string token) + { + this.SmtpClient.Authenticate(new SaslMechanismOAuth2(username, token)); + } + + public Task AuthenticateAsync(string username, string token, CancellationToken cancellationToken = default(CancellationToken)) + { + return this.SmtpClient.AuthenticateAsync(new SaslMechanismOAuth2(username, token), cancellationToken); + } + } + } +} diff --git a/DNN Platform/Library/Services/Mail/MailProvider.cs b/DNN Platform/Library/Services/Mail/MailProvider.cs index fdc9c8dbbf5..e1a1adb38e8 100644 --- a/DNN Platform/Library/Services/Mail/MailProvider.cs +++ b/DNN Platform/Library/Services/Mail/MailProvider.cs @@ -1,37 +1,40 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information -namespace DotNetNuke.Services.Mail -{ - using System.Threading; - using System.Threading.Tasks; - - using DotNetNuke.ComponentModel; +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information +namespace DotNetNuke.Services.Mail +{ + using System.Threading; + using System.Threading.Tasks; - /// A provider with the ability to send emails. - public abstract class MailProvider - { - /// Gets the currently configured instance. - /// A instance. - public static MailProvider Instance() - { - return ComponentFactory.GetComponent(); - } - - /// Sends an email. - /// Information about the message to send. - /// Information about the SMTP server via which to send the message. - /// if the message send successfully, otherwise an error message. - public abstract string SendMail(MailInfo mailInfo, SmtpInfo smtpInfo = null); - - /// Sends an email. - /// Information about the message to send. - /// Information about the SMTP server via which to send the message. - /// The cancellation token. - /// if the message send successfully, otherwise an error message. - public virtual Task SendMailAsync(MailInfo mailInfo, SmtpInfo smtpInfo = null, CancellationToken cancellationToken = default(CancellationToken)) - { - return Task.FromResult(this.SendMail(mailInfo, smtpInfo)); - } - } -} + using DotNetNuke.ComponentModel; + + /// A provider with the ability to send emails. + public abstract class MailProvider + { + /// Gets a value indicating whether this provider supports OAuth authentication to the SMTP server. + public virtual bool SupportsOAuth => false; + + /// Gets the currently configured instance. + /// A instance. + public static MailProvider Instance() + { + return ComponentFactory.GetComponent(); + } + + /// Sends an email. + /// Information about the message to send. + /// Information about the SMTP server via which to send the message. + /// if the message send successfully, otherwise an error message. + public abstract string SendMail(MailInfo mailInfo, SmtpInfo smtpInfo = null); + + /// Sends an email. + /// Information about the message to send. + /// Information about the SMTP server via which to send the message. + /// The cancellation token. + /// if the message send successfully, otherwise an error message. + public virtual Task SendMailAsync(MailInfo mailInfo, SmtpInfo smtpInfo = null, CancellationToken cancellationToken = default(CancellationToken)) + { + return Task.FromResult(this.SendMail(mailInfo, smtpInfo)); + } + } +} diff --git a/DNN Platform/Library/Services/Mail/OAuth/IOAuth2SmtpClient.cs b/DNN Platform/Library/Services/Mail/OAuth/IOAuth2SmtpClient.cs new file mode 100644 index 00000000000..8f4adc54b52 --- /dev/null +++ b/DNN Platform/Library/Services/Mail/OAuth/IOAuth2SmtpClient.cs @@ -0,0 +1,24 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information +namespace DotNetNuke.Services.Mail.OAuth +{ + using System.Threading; + using System.Threading.Tasks; + + /// A contract specifying the ability to authenticate an SMTP client with an OAuth 2 endpoint. + public interface IOAuth2SmtpClient + { + /// Authenticates this SMTP client with the given OAuth credentials. + /// The username. + /// The auth token. + void Authenticate(string username, string token); + + /// Authenticates this SMTP client with the given OAuth credentials. + /// The username. + /// The auth token. + /// The cancellation token. + /// A indicating completion. + Task AuthenticateAsync(string username, string token, CancellationToken cancellationToken = default(CancellationToken)); + } +} diff --git a/DNN Platform/Library/Services/Mail/OAuth/ISmtpOAuthController.cs b/DNN Platform/Library/Services/Mail/OAuth/ISmtpOAuthController.cs new file mode 100644 index 00000000000..f5713feabf7 --- /dev/null +++ b/DNN Platform/Library/Services/Mail/OAuth/ISmtpOAuthController.cs @@ -0,0 +1,20 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information +namespace DotNetNuke.Services.Mail.OAuth +{ + using System.Collections.Generic; + + /// A contract specifying the ability to retrieve the SMTP OAuth providers. + public interface ISmtpOAuthController + { + /// Get all the OAuth providers. + /// OAuth providers list. + IReadOnlyCollection GetOAuthProviders(); + + /// Get an OAuth provider by name. + /// The provider name. + /// The OAuth provider or . + ISmtpOAuthProvider GetOAuthProvider(string name); + } +} diff --git a/DNN Platform/Library/Services/Mail/OAuth/ISmtpOAuthProvider.cs b/DNN Platform/Library/Services/Mail/OAuth/ISmtpOAuthProvider.cs new file mode 100644 index 00000000000..56fa0a43f47 --- /dev/null +++ b/DNN Platform/Library/Services/Mail/OAuth/ISmtpOAuthProvider.cs @@ -0,0 +1,61 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information +namespace DotNetNuke.Services.Mail.OAuth +{ + using System.Collections.Generic; + using System.Threading; + using System.Threading.Tasks; + + using DotNetNuke.Common.Utilities; + + /// A contract specifying the ability to authenticate an SMTP client with an OAuth 2 endpoint. + public interface ISmtpOAuthProvider + { + /// Gets provider name. + string Name { get; } + + /// Gets the localized name. + string LocalizedName { get; } + + /// Whether the provider has completed the authorization process for the portal. + /// The portal ID. + /// if the authorization has been completed, otherwise .. + bool IsAuthorized(int portalId); + + /// Whether the provider has completed the authorization process for the portal. + /// The portal ID. + /// The cancellation token. + /// if the authorization has been completed, otherwise .. + Task IsAuthorizedAsync(int portalId, CancellationToken cancellationToken = default); + + /// Get the authorize URL. + /// The portal ID. + /// The URL. + string GetAuthorizeUrl(int portalId); + + /// Get the provider parameters. + /// the portal ID of the setting, pass if it's a global setting. + /// The list of settings. + IList GetSettings(int portalId); + + /// Update provider settings. + /// The portal ID of the setting, pass if it's a global setting. + /// The settings. + /// The errors. + /// Whether the settings changed. + bool UpdateSettings(int portalId, IDictionary settings, out IList errorMessages); + + /// Authorize the SMTP client. + /// The portal ID. + /// The SMTP client. + void Authorize(int portalId, IOAuth2SmtpClient smtpClient); + + /// Authorize the SMTP client. + /// The portal ID. + /// The SMTP client. + /// The cancellation token. + /// A indicating completion. + Task AuthorizeAsync(int portalId, IOAuth2SmtpClient smtpClient, CancellationToken cancellationToken = default); + } +} diff --git a/DNN Platform/Library/Services/Mail/OAuth/SmtpOAuthController.cs b/DNN Platform/Library/Services/Mail/OAuth/SmtpOAuthController.cs new file mode 100644 index 00000000000..95e3bef358f --- /dev/null +++ b/DNN Platform/Library/Services/Mail/OAuth/SmtpOAuthController.cs @@ -0,0 +1,48 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information +namespace DotNetNuke.Services.Mail.OAuth +{ + using System.Collections.Generic; + using System.Linq; + + using DotNetNuke.DependencyInjection.Extensions; + + using Microsoft.Extensions.DependencyInjection; + using Microsoft.Extensions.DependencyInjection.Extensions; + + /// SMTP OAuth controller. + public class SmtpOAuthController : ISmtpOAuthController + { + private readonly IEnumerable smtpOAuthProviders; + + /// Initializes a new instance of the class. + /// The SMTP OAuth providers. + public SmtpOAuthController(IEnumerable smtpOAuthProviders) + { + this.smtpOAuthProviders = smtpOAuthProviders; + } + + /// Registers all of the types with the . + /// The services collection. + public static void RegisterOAuthProviders(IServiceCollection serviceCollection) + { + var providerTypes = TypeExtensions.SafeGetTypes() + .Types.Where(t => t is { IsClass: true, IsAbstract: false } && typeof(ISmtpOAuthProvider).IsAssignableFrom(t)); + + serviceCollection.TryAddEnumerable(providerTypes.Select(t => ServiceDescriptor.Transient(typeof(ISmtpOAuthProvider), t))); + } + + /// + public IReadOnlyCollection GetOAuthProviders() + { + return this.smtpOAuthProviders.ToList(); + } + + /// + public ISmtpOAuthProvider GetOAuthProvider(string name) + { + return this.smtpOAuthProviders.FirstOrDefault(i => i.Name == name); + } + } +} diff --git a/DNN Platform/Library/Services/Mail/OAuth/SmtpOAuthSetting.cs b/DNN Platform/Library/Services/Mail/OAuth/SmtpOAuthSetting.cs new file mode 100644 index 00000000000..97f6a974320 --- /dev/null +++ b/DNN Platform/Library/Services/Mail/OAuth/SmtpOAuthSetting.cs @@ -0,0 +1,41 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information +namespace DotNetNuke.Services.Mail.OAuth +{ + using System; + using System.Runtime.Serialization; + + /// Smtp auth setting. + [DataContract] + public class SmtpOAuthSetting + { + /// Gets or sets the setting name. + [DataMember(Name = "name")] + public string Name { get; set; } + + /// Gets or sets the setting value. + [DataMember(Name = "value")] + public string Value { get; set; } + + /// Gets or sets the setting label. + [DataMember(Name = "label")] + public string Label { get; set; } + + /// Gets or sets the setting help text. + [DataMember(Name = "help")] + public string Help { get; set; } + + /// Gets or sets a value indicating whether this is a secure setting. + [DataMember(Name = "isSecure")] + public bool IsSecure { get; set; } + + /// Gets or sets a value indicating whether this is a required setting. + [DataMember(Name = "isRequired")] + public bool IsRequired { get; set; } + + /// Gets or sets a value indicating whether this setting is only used in server side. + [IgnoreDataMember] + public bool IsBackground { get; set; } + } +} diff --git a/DNN Platform/Library/Services/Mail/SMTPInfo.cs b/DNN Platform/Library/Services/Mail/SMTPInfo.cs index 1e5f05b6c26..6851089bd8f 100644 --- a/DNN Platform/Library/Services/Mail/SMTPInfo.cs +++ b/DNN Platform/Library/Services/Mail/SMTPInfo.cs @@ -20,5 +20,10 @@ public class SmtpInfo /// Gets or sets a value indicating whether SSL should be enabled or disabled. public bool EnableSSL { get; set; } + + /// + /// Gets or sets SMTP OAuth provider. + /// + public string AuthProvider { get; set; } } } diff --git a/DNN Platform/Library/Services/Scheduling/Scheduler.cs b/DNN Platform/Library/Services/Scheduling/Scheduler.cs index 4af1ee88c23..ae2a5c4b957 100644 --- a/DNN Platform/Library/Services/Scheduling/Scheduler.cs +++ b/DNN Platform/Library/Services/Scheduling/Scheduler.cs @@ -108,7 +108,7 @@ public static ScheduleHistoryItem AddScheduleHistory(ScheduleHistoryItem schedul /// /// Checks the scheduled item if it has servers specified to run on. If it does, then it checks to see if the server is active. /// - /// The schedule to check + /// The schedule to check. /// True if nothing happens to the scheduled item. Returns false if the scheduled item was updated. /// /// If the server specified is not active then the scheduled item will be assigned to the most recent active server. diff --git a/DNN Platform/Library/Services/Scheduling/SchedulingController.cs b/DNN Platform/Library/Services/Scheduling/SchedulingController.cs index 280c6a3889b..59c822a4923 100644 --- a/DNN Platform/Library/Services/Scheduling/SchedulingController.cs +++ b/DNN Platform/Library/Services/Scheduling/SchedulingController.cs @@ -12,15 +12,16 @@ namespace DotNetNuke.Services.Scheduling using DotNetNuke.Entities.Host; using DotNetNuke.Entities.Portals; using DotNetNuke.Entities.Users; + using DotNetNuke.Internal.SourceGenerators; using DotNetNuke.Services.Log.EventLog; using Microsoft.VisualBasic; using Globals = DotNetNuke.Common.Globals; - public class SchedulingController + public partial class SchedulingController { - [Obsolete("Obsoleted in 7.3.0 - use alternate overload. Scheduled removal in v10.0.0.")] - public static int AddSchedule(string typeFullName, int timeLapse, string timeLapseMeasurement, int retryTimeLapse, string retryTimeLapseMeasurement, int retainHistoryNum, string attachToEvent, bool catchUpEnabled, bool enabled, string objectDependencies, string servers, string friendlyName) + [DnnDeprecated(7, 3, 0, "Use alternate overload", RemovalVersion = 10)] + public static partial int AddSchedule(string typeFullName, int timeLapse, string timeLapseMeasurement, int retryTimeLapse, string retryTimeLapseMeasurement, int retainHistoryNum, string attachToEvent, bool catchUpEnabled, bool enabled, string objectDependencies, string servers, string friendlyName) { return AddSchedule( typeFullName, @@ -210,8 +211,8 @@ public static void UpdateSchedule(int scheduleID, string typeFullName, int timeL #pragma warning restore 618 } - [Obsolete("Obsoleted in 7.3.0 - use alternate overload. Scheduled removal in v10.0.0.")] - public static void UpdateSchedule(int scheduleID, string typeFullName, int timeLapse, string timeLapseMeasurement, int retryTimeLapse, string retryTimeLapseMeasurement, int retainHistoryNum, string attachToEvent, bool catchUpEnabled, bool enabled, string objectDependencies, string servers, string friendlyName, DateTime scheduleStartDate) + [DnnDeprecated(7, 3, 0, "Use alternate overload", RemovalVersion = 10)] + public static partial void UpdateSchedule(int scheduleID, string typeFullName, int timeLapse, string timeLapseMeasurement, int retryTimeLapse, string retryTimeLapseMeasurement, int retainHistoryNum, string attachToEvent, bool catchUpEnabled, bool enabled, string objectDependencies, string servers, string friendlyName, DateTime scheduleStartDate) { DataProvider.Instance().UpdateSchedule( scheduleID, @@ -261,8 +262,8 @@ public static bool CanRunOnThisServer(string servers) /// /// Replaces the old server name, with the new server name on all schedules where the old server name was found. /// - /// The old server to replace - /// The new server to use + /// The old server to replace. + /// The new server to use. internal static void ReplaceServer(ServerInfo oldServer, ServerInfo newServer) { DataProvider.Instance().ReplaceServerOnSchedules(oldServer.ServerName, newServer.ServerName); diff --git a/DNN Platform/Library/Services/Scheduling/SchedulingProvider.cs b/DNN Platform/Library/Services/Scheduling/SchedulingProvider.cs index 5603561213a..801f8fcbc55 100644 --- a/DNN Platform/Library/Services/Scheduling/SchedulingProvider.cs +++ b/DNN Platform/Library/Services/Scheduling/SchedulingProvider.cs @@ -7,7 +7,7 @@ namespace DotNetNuke.Services.Scheduling using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; - using System.Linq; + using DotNetNuke.Common.Utilities; using DotNetNuke.ComponentModel; using DotNetNuke.Entities.Controllers; diff --git a/DNN Platform/Library/Services/Search/IndexingProvider.cs b/DNN Platform/Library/Services/Search/IndexingProvider.cs index 2b371f369cc..e16661437e0 100644 --- a/DNN Platform/Library/Services/Search/IndexingProvider.cs +++ b/DNN Platform/Library/Services/Search/IndexingProvider.cs @@ -8,13 +8,14 @@ namespace DotNetNuke.Services.Search using System.Linq; using DotNetNuke.Common; + using DotNetNuke.Internal.SourceGenerators; using DotNetNuke.Services.Scheduling; using DotNetNuke.Services.Search.Entities; using DotNetNuke.Services.Search.Internals; /// A base class for search indexers. - [Obsolete("Legacy Indexing base class -- Deprecated in DNN 7.1. Use 'IndexingProviderBase' instead.. Scheduled removal in v10.0.0.")] - public abstract class IndexingProvider + [DnnDeprecated(7, 1, 0, "Use 'IndexingProviderBase' instead", RemovalVersion = 10)] + public abstract partial class IndexingProvider { private const string TimePostfix = "UtcTime"; private const string DataPostfix = "Data"; @@ -29,13 +30,13 @@ public virtual int IndexSearchDocuments(int portalId, ScheduleHistoryItem schedu throw new NotImplementedException(); } - [Obsolete("Deprecated in DNN 7.4.2 Use 'IndexSearchDocuments' instead for lower memory footprint during search.. Scheduled removal in v10.0.0.")] - public virtual IEnumerable GetSearchDocuments(int portalId, DateTime startDateLocal) + [DnnDeprecated(7, 4, 2, "Use 'IndexSearchDocuments' instead for lower memory footprint during search", RemovalVersion = 10)] + public virtual partial IEnumerable GetSearchDocuments(int portalId, DateTime startDateLocal) { return Enumerable.Empty(); } - [Obsolete("Legacy Search (ISearchable) -- Deprecated in DNN 7.1. Use 'IndexSearchDocuments' instead.. Scheduled removal in v10.0.0.")] + [Obsolete("Deprecated in DotNetNuke 7.1.0. Use 'IndexSearchDocuments' instead. Scheduled for removal in v10.0.0.")] public abstract SearchItemInfoCollection GetSearchIndexItems(int portalId); /// Retrieves the date/time of the last item to be indexed. diff --git a/DNN Platform/Library/Services/Search/IndexingProviderBase.cs b/DNN Platform/Library/Services/Search/IndexingProviderBase.cs index 37cda85a5ff..ae4015dbf94 100644 --- a/DNN Platform/Library/Services/Search/IndexingProviderBase.cs +++ b/DNN Platform/Library/Services/Search/IndexingProviderBase.cs @@ -8,12 +8,13 @@ namespace DotNetNuke.Services.Search using System.Linq; using DotNetNuke.Common; + using DotNetNuke.Internal.SourceGenerators; using DotNetNuke.Services.Scheduling; using DotNetNuke.Services.Search.Entities; using DotNetNuke.Services.Search.Internals; /// A base class for search indexers. - public abstract class IndexingProviderBase + public abstract partial class IndexingProviderBase { private const string TimePostfix = "UtcTime"; private const string DataPostfix = "Data"; @@ -25,14 +26,14 @@ public abstract class IndexingProviderBase /// The number of documents indexed. public abstract int IndexSearchDocuments(int portalId, ScheduleHistoryItem schedule, DateTime startDateLocal, Action> indexer); - [Obsolete("Deprecated in DNN 7.4.2 Use 'IndexSearchDocuments' instead for lower memory footprint during search.. Scheduled removal in v10.0.0.")] - public virtual IEnumerable GetSearchDocuments(int portalId, DateTime startDateLocal) + [DnnDeprecated(7, 4, 2, "Use 'IndexSearchDocuments' instead for lower memory footprint during search", RemovalVersion = 10)] + public virtual partial IEnumerable GetSearchDocuments(int portalId, DateTime startDateLocal) { return Enumerable.Empty(); } - [Obsolete("Legacy Search (ISearchable) -- Deprecated in DNN 7.1. Use 'IndexSearchDocuments' instead.. Scheduled removal in v10.0.0.")] - public virtual SearchItemInfoCollection GetSearchIndexItems(int portalId) + [DnnDeprecated(7, 1, 0, "Use 'IndexSearchDocuments' instead", RemovalVersion = 10)] + public virtual partial SearchItemInfoCollection GetSearchIndexItems(int portalId) { return new SearchItemInfoCollection(); } diff --git a/DNN Platform/Library/Services/Search/SearchConfig.cs b/DNN Platform/Library/Services/Search/SearchConfig.cs index 3cbe22e0529..17d68d8d404 100644 --- a/DNN Platform/Library/Services/Search/SearchConfig.cs +++ b/DNN Platform/Library/Services/Search/SearchConfig.cs @@ -10,11 +10,12 @@ namespace DotNetNuke.Services.Search using DotNetNuke.Entities.Host; using DotNetNuke.Entities.Portals; using DotNetNuke.Instrumentation; + using DotNetNuke.Internal.SourceGenerators; /// The SearchConfig class provides a configuration class for Search. - [Obsolete("Deprecated in DNN 7.1. No longer used in the Search infrastructure.. Scheduled removal in v10.0.0.")] + [DnnDeprecated(7, 1, 0, "No longer used in the Search infrastructure", RemovalVersion = 10)] [Serializable] - public class SearchConfig + public partial class SearchConfig { private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(SearchConfig)); private readonly bool searchIncludeCommon; diff --git a/DNN Platform/Library/Services/Search/SearchCriteria.cs b/DNN Platform/Library/Services/Search/SearchCriteria.cs index eea9b27eab7..5105d8a4a00 100644 --- a/DNN Platform/Library/Services/Search/SearchCriteria.cs +++ b/DNN Platform/Library/Services/Search/SearchCriteria.cs @@ -2,21 +2,21 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information -namespace DotNetNuke.Services.Search -{ - using System; +namespace DotNetNuke.Services.Search +{ + using DotNetNuke.Internal.SourceGenerators; - /// Namespace: DotNetNuke.Services.Search - /// Project: DotNetNuke.Search.DataStore - /// Class: SearchCriteria - /// The SearchCriteria represents a search criterion. - [Obsolete("Deprecated in DNN 7.1. No longer used in the Search infrastructure.. Scheduled removal in v10.0.0.")] - public class SearchCriteria - { - public string Criteria { get; set; } - - public bool MustExclude { get; set; } - - public bool MustInclude { get; set; } - } -} + /// Namespace: DotNetNuke.Services.Search + /// Project: DotNetNuke.Search.DataStore + /// Class: SearchCriteria + /// The SearchCriteria represents a search criterion. + [DnnDeprecated(7, 1, 0, "No longer used in the Search infrastructure", RemovalVersion = 10)] + public partial class SearchCriteria + { + public string Criteria { get; set; } + + public bool MustExclude { get; set; } + + public bool MustInclude { get; set; } + } +} diff --git a/DNN Platform/Library/Services/Search/SearchCriteriaCollection.cs b/DNN Platform/Library/Services/Search/SearchCriteriaCollection.cs index d9a26c6dda0..594d0c800fa 100644 --- a/DNN Platform/Library/Services/Search/SearchCriteriaCollection.cs +++ b/DNN Platform/Library/Services/Search/SearchCriteriaCollection.cs @@ -3,12 +3,13 @@ // See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Search { - using System; using System.Collections; + using DotNetNuke.Internal.SourceGenerators; + /// Represents a collection of SearchCriteria objects. - [Obsolete("Deprecated in DNN 7.1. No longer used in the Search infrastructure.. Scheduled removal in v10.0.0.")] - public class SearchCriteriaCollection : CollectionBase + [DnnDeprecated(7, 1, 0, "No longer used in the Search infrastructure", RemovalVersion = 10)] + public partial class SearchCriteriaCollection : CollectionBase { /// Initializes a new instance of the class. public SearchCriteriaCollection() diff --git a/DNN Platform/Library/Services/Search/SearchDataStore.cs b/DNN Platform/Library/Services/Search/SearchDataStore.cs index a9ce0eb8f36..c8242a67709 100644 --- a/DNN Platform/Library/Services/Search/SearchDataStore.cs +++ b/DNN Platform/Library/Services/Search/SearchDataStore.cs @@ -3,7 +3,6 @@ // See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Search { - using System; using System.Collections; using System.Collections.Generic; using System.Data; @@ -14,6 +13,7 @@ namespace DotNetNuke.Services.Search using DotNetNuke.Entities.Modules; using DotNetNuke.Entities.Portals; using DotNetNuke.Entities.Tabs; + using DotNetNuke.Internal.SourceGenerators; using DotNetNuke.Security.Permissions; using DotNetNuke.Services.Search.Internals; @@ -24,8 +24,8 @@ namespace DotNetNuke.Services.Search /// The SearchDataStore is an implementation of the abstract SearchDataStoreProvider /// class. /// - [Obsolete("Deprecated in DNN 7.1. No longer used in the Search infrastructure.. Scheduled removal in v10.0.0.")] - public class SearchDataStore : SearchDataStoreProvider + [DnnDeprecated(7, 1, 0, "No longer used in the Search infrastructure", RemovalVersion = 10)] + public partial class SearchDataStore : SearchDataStoreProvider { /// public override SearchResultsInfoCollection GetSearchItems(int portalId, int tabId, int moduleId) diff --git a/DNN Platform/Library/Services/Search/SearchDataStoreController.cs b/DNN Platform/Library/Services/Search/SearchDataStoreController.cs index fe1ec3eb646..652f0c0fd61 100644 --- a/DNN Platform/Library/Services/Search/SearchDataStoreController.cs +++ b/DNN Platform/Library/Services/Search/SearchDataStoreController.cs @@ -10,46 +10,47 @@ namespace DotNetNuke.Services.Search using DotNetNuke.Common.Utilities; using DotNetNuke.Data; + using DotNetNuke.Internal.SourceGenerators; /// The SearchDataStoreController is the Business Controller class for SearchDataStore. - [Obsolete("Deprecated in DNN 7.1. No longer used in the Search infrastructure.. Scheduled removal in v10.0.0.")] - public class SearchDataStoreController + [DnnDeprecated(7, 1, 0, "No longer used in the Search infrastructure", RemovalVersion = 10)] + public partial class SearchDataStoreController { - [Obsolete("Deprecated in DNN 7.2.2 Implementation changed to return a NullInteger value. Scheduled removal in v10.0.0.")] - public static int AddSearchItem(SearchItemInfo item) + [DnnDeprecated(7, 2, 2, "Implementation changed to return a NullInteger value", RemovalVersion = 10)] + public static partial int AddSearchItem(SearchItemInfo item) { return Null.NullInteger; } - [Obsolete("Deprecated in DNN 7.2.2 Implementation changed to do nothing. Scheduled removal in v10.0.0.")] - public static void DeleteSearchItem(int searchItemId) + [DnnDeprecated(7, 2, 2, "Implementation changed to do nothing", RemovalVersion = 10)] + public static partial void DeleteSearchItem(int searchItemId) { } - [Obsolete("Deprecated in DNN 7.2.2 Implementation changed to do nothing. Scheduled removal in v10.0.0.")] - public static void DeleteSearchItemWords(int searchItemId) + [DnnDeprecated(7, 2, 2, "Implementation changed to do nothing", RemovalVersion = 10)] + public static partial void DeleteSearchItemWords(int searchItemId) { } /// An empty . - [Obsolete("Deprecated in DNN 7.1.2 Implementation changed to return empty result set. Scheduled removal in v10.0.0.")] - public static SearchItemInfo GetSearchItem(int moduleId, string searchKey) + [DnnDeprecated(7, 2, 2, "Implementation changed to return empty result set", RemovalVersion = 10)] + public static partial SearchItemInfo GetSearchItem(int moduleId, string searchKey) { var empty = new SearchItemInfo(); return empty; } /// An empty . - [Obsolete("Deprecated in DNN 7.1.2 Implementation changed to return empty result set. Scheduled removal in v10.0.0.")] - public static Dictionary GetSearchItems(int moduleId) + [DnnDeprecated(7, 2, 2, "Implementation changed to return empty result set", RemovalVersion = 10)] + public static partial Dictionary GetSearchItems(int moduleId) { var empty = new Dictionary(); return empty; } /// An empty . - [Obsolete("Deprecated in DNN 7.1.2 Implementation changed to return empty result set. Scheduled removal in v10.0.0.")] - public static ArrayList GetSearchItems(int portalId, int tabId, int moduleId) + [DnnDeprecated(7, 2, 2, "Implementation changed to return empty result set", RemovalVersion = 10)] + public static partial ArrayList GetSearchItems(int portalId, int tabId, int moduleId) { var empty = new ArrayList(); return empty; @@ -59,16 +60,16 @@ public static ArrayList GetSearchItems(int portalId, int tabId, int moduleId) /// A Id of the Portal. /// The word. /// An empty . - [Obsolete("Deprecated in DNN 7.1.2 Implementation changed to return empty result set. Scheduled removal in v10.0.0.")] - public static SearchResultsInfoCollection GetSearchResults(int portalID, string word) + [DnnDeprecated(7, 2, 2, "Implementation changed to return empty result set", RemovalVersion = 10)] + public static partial SearchResultsInfoCollection GetSearchResults(int portalID, string word) { var empty = new SearchResultsInfoCollection(); return empty; } /// An empty . - [Obsolete("Deprecated in DNN 7.1.2 Implementation changed to return empty result set. Scheduled removal in v10.0.0.")] - public static SearchResultsInfoCollection GetSearchResults(int portalId, int tabId, int moduleId) + [DnnDeprecated(7, 2, 2, "Implementation changed to return empty result set", RemovalVersion = 10)] + public static partial SearchResultsInfoCollection GetSearchResults(int portalId, int tabId, int moduleId) { var empty = new SearchResultsInfoCollection(); return empty; @@ -108,8 +109,8 @@ public static Dictionary GetSearchSettings(int moduleId) return dicSearchSettings; } - [Obsolete("Deprecated in DNN 7.2.2 Implementation changed to do nothing. Scheduled removal in v10.0.0.")] - public static void UpdateSearchItem(SearchItemInfo item) + [DnnDeprecated(7, 2, 2, "Implementation changed to do nothing", RemovalVersion = 10)] + public static partial void UpdateSearchItem(SearchItemInfo item) { } } diff --git a/DNN Platform/Library/Services/Search/SearchDataStoreProvider.cs b/DNN Platform/Library/Services/Search/SearchDataStoreProvider.cs index efd9ae28a5c..b46d22d24bc 100644 --- a/DNN Platform/Library/Services/Search/SearchDataStoreProvider.cs +++ b/DNN Platform/Library/Services/Search/SearchDataStoreProvider.cs @@ -3,12 +3,11 @@ // See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Search { - using System; - using DotNetNuke.ComponentModel; + using DotNetNuke.Internal.SourceGenerators; - [Obsolete("Deprecated in DNN 7.1. No longer used in the Search infrastructure.. Scheduled removal in v10.0.0.")] - public abstract class SearchDataStoreProvider + [DnnDeprecated(7, 1, 0, "No longer used in the Search infrastructure", RemovalVersion = 10)] + public abstract partial class SearchDataStoreProvider { // return the provider public static SearchDataStoreProvider Instance() diff --git a/DNN Platform/Library/Services/Search/SearchEngine.cs b/DNN Platform/Library/Services/Search/SearchEngine.cs index fefa0928b67..37d24ff86e9 100644 --- a/DNN Platform/Library/Services/Search/SearchEngine.cs +++ b/DNN Platform/Library/Services/Search/SearchEngine.cs @@ -12,13 +12,14 @@ namespace DotNetNuke.Services.Search using DotNetNuke.Data; using DotNetNuke.Entities.Controllers; using DotNetNuke.Entities.Portals; + using DotNetNuke.Internal.SourceGenerators; using DotNetNuke.Services.Scheduling; using DotNetNuke.Services.Search.Entities; using DotNetNuke.Services.Search.Internals; using Newtonsoft.Json; /// The SearchEngine manages the Indexing of the Portal content. - internal class SearchEngine + internal partial class SearchEngine { /// Initializes a new instance of the class. /// @@ -143,8 +144,8 @@ internal void Commit() /// /// The Index Provider that will index the content of the portal. /// A new instance. - [Obsolete("Legacy Search (ISearchable) -- Deprecated in DNN 7.1. Use 'IndexSearchDocuments' instead.. Scheduled removal in v10.0.0.")] - protected SearchItemInfoCollection GetContent(IndexingProviderBase indexer) + [DnnDeprecated(7, 1, 0, "Use 'IndexSearchDocuments' instead")] + protected partial SearchItemInfoCollection GetContent(IndexingProviderBase indexer) { var searchItems = new SearchItemInfoCollection(); var portals = PortalController.Instance.GetPortals(); @@ -166,8 +167,8 @@ protected SearchItemInfoCollection GetContent(IndexingProviderBase indexer) /// The Id of the Portal. /// The Index Provider that will index the content of the portal. /// A new instance. - [Obsolete("Legacy Search (ISearchable) -- Deprecated in DNN 7.1. Use 'IndexSearchDocuments' instead.. Scheduled removal in v10.0.0.")] - protected SearchItemInfoCollection GetContent(int portalId, IndexingProvider indexer) + [DnnDeprecated(7, 1, 0, "Use 'IndexSearchDocuments' instead", RemovalVersion = 10)] + protected partial SearchItemInfoCollection GetContent(int portalId, IndexingProvider indexer) { var searchItems = new SearchItemInfoCollection(); searchItems.AddRange(indexer.GetSearchIndexItems(portalId)); diff --git a/DNN Platform/Library/Services/Search/SearchItemInfo.cs b/DNN Platform/Library/Services/Search/SearchItemInfo.cs index 2be9026a87d..d716f10317e 100644 --- a/DNN Platform/Library/Services/Search/SearchItemInfo.cs +++ b/DNN Platform/Library/Services/Search/SearchItemInfo.cs @@ -6,14 +6,15 @@ namespace DotNetNuke.Services.Search using System; using DotNetNuke.Common.Utilities; + using DotNetNuke.Internal.SourceGenerators; /// Namespace: DotNetNuke.Services.Search /// Project: DotNetNuke /// Class: SearchItemInfo /// The SearchItemInfo represents a Search Item. - [Obsolete("Deprecated in DNN 7.1. No longer used in the Search infrastructure.. Scheduled removal in v10.0.0.")] + [DnnDeprecated(7, 1, 0, "No longer used in the Search infrastructure", RemovalVersion = 10)] [Serializable] - public class SearchItemInfo + public partial class SearchItemInfo { private int author; private string content; diff --git a/DNN Platform/Library/Services/Search/SearchItemInfoCollection.cs b/DNN Platform/Library/Services/Search/SearchItemInfoCollection.cs index ea25de600e7..5fdcd99f610 100644 --- a/DNN Platform/Library/Services/Search/SearchItemInfoCollection.cs +++ b/DNN Platform/Library/Services/Search/SearchItemInfoCollection.cs @@ -6,10 +6,12 @@ namespace DotNetNuke.Services.Search using System; using System.Collections; + using DotNetNuke.Internal.SourceGenerators; + /// Represents a collection of SearchItemInfo objects. - [Obsolete("Deprecated in DNN 7.1. No longer used in the Search infrastructure.. Scheduled removal in v10.0.0.")] + [DnnDeprecated(7, 1, 0, "No longer used in the Search infrastructure", RemovalVersion = 10)] [Serializable] - public class SearchItemInfoCollection : CollectionBase + public partial class SearchItemInfoCollection : CollectionBase { /// Initializes a new instance of the class. public SearchItemInfoCollection() diff --git a/DNN Platform/Library/Services/Search/SearchResultsInfo.cs b/DNN Platform/Library/Services/Search/SearchResultsInfo.cs index d5305107271..b8596351f0d 100644 --- a/DNN Platform/Library/Services/Search/SearchResultsInfo.cs +++ b/DNN Platform/Library/Services/Search/SearchResultsInfo.cs @@ -5,13 +5,15 @@ namespace DotNetNuke.Services.Search { using System; + using DotNetNuke.Internal.SourceGenerators; + /// Namespace: DotNetNuke.Services.Search /// Project: DotNetNuke /// Class: SearchResultsInfo /// The SearchResultsInfo represents a Search Result Item. - [Obsolete("Deprecated in DNN 7.1. No longer used in the Search infrastructure.. Scheduled removal in v10.0.0.")] + [DnnDeprecated(7, 1, 0, "No longer used in the Search infrastructure", RemovalVersion = 10)] [Serializable] - public class SearchResultsInfo + public partial class SearchResultsInfo { private string author; private string authorName; diff --git a/DNN Platform/Library/Services/Search/SearchResultsInfoCollection.cs b/DNN Platform/Library/Services/Search/SearchResultsInfoCollection.cs index 5eb0579f2cb..b9c498b18fe 100644 --- a/DNN Platform/Library/Services/Search/SearchResultsInfoCollection.cs +++ b/DNN Platform/Library/Services/Search/SearchResultsInfoCollection.cs @@ -6,10 +6,12 @@ namespace DotNetNuke.Services.Search using System; using System.Collections; + using DotNetNuke.Internal.SourceGenerators; + /// Represents a collection of objects. - [Obsolete("Deprecated in DNN 7.1. No longer used in the Search infrastructure.. Scheduled removal in v10.0.0.")] + [DnnDeprecated(7, 1, 0, "No longer used in the Search infrastructure", RemovalVersion = 10)] [Serializable] - public class SearchResultsInfoCollection : CollectionBase + public partial class SearchResultsInfoCollection : CollectionBase { /// Initializes a new instance of the class. public SearchResultsInfoCollection() diff --git a/DNN Platform/Library/Services/SystemDateTime/SystemDateTime.cs b/DNN Platform/Library/Services/SystemDateTime/SystemDateTime.cs index 9c22705a4a5..9b184da8487 100644 --- a/DNN Platform/Library/Services/SystemDateTime/SystemDateTime.cs +++ b/DNN Platform/Library/Services/SystemDateTime/SystemDateTime.cs @@ -1,33 +1,34 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information -namespace DotNetNuke.Services.SystemDateTime -{ - using System; +namespace DotNetNuke.Services.SystemDateTime +{ + using System; - using DotNetNuke.Data; + using DotNetNuke.Data; + using DotNetNuke.Internal.SourceGenerators; - /// The SystemDateTime provides static method to obtain System's Time. - /// - /// DateTime information is collected from Database. The methods are created to find one unified timestamp from database - /// as opposed to depending on web server's timestamp. This method becomes more relevant in a web farm configuration. - /// - public class SystemDateTime - { - private static readonly DataProvider Provider = DataProvider.Instance(); - - [Obsolete("Deprecated in DNN 7.1.2. Replaced by DateUtils.GetDatabaseUtcTime, which includes caching. Scheduled removal in v10.0.0.")] - public static DateTime GetCurrentTimeUtc() - { - return Provider.GetDatabaseTimeUtc(); - } - - /// GetCurrentTime get current time from database. - /// DateTime. - [Obsolete("Deprecated in DNN 9.1.0. Replaced by DateUtils.GetDatabaseLocalTime, which includes caching. Scheduled removal in v11.0.0.")] - public static DateTime GetCurrentTime() - { - return Provider.GetDatabaseTime(); - } - } -} + /// The SystemDateTime provides static method to obtain System's Time. + /// + /// DateTime information is collected from Database. The methods are created to find one unified timestamp from database + /// as opposed to depending on web server's timestamp. This method becomes more relevant in a web farm configuration. + /// + public partial class SystemDateTime + { + private static readonly DataProvider Provider = DataProvider.Instance(); + + [DnnDeprecated(7, 1, 2, "Replaced by DateUtils.GetDatabaseUtcTime, which includes caching", RemovalVersion = 10)] + public static partial DateTime GetCurrentTimeUtc() + { + return Provider.GetDatabaseTimeUtc(); + } + + /// GetCurrentTime get current time from database. + /// DateTime. + [DnnDeprecated(9, 1, 0, "Replaced by DateUtils.GetDatabaseLocalTime, which includes caching", RemovalVersion = 10)] + public static partial DateTime GetCurrentTime() + { + return Provider.GetDatabaseTime(); + } + } +} diff --git a/DNN Platform/Library/Services/SystemHealth/WebServerMonitor.cs b/DNN Platform/Library/Services/SystemHealth/WebServerMonitor.cs index a534028c81e..b99efe691fc 100644 --- a/DNN Platform/Library/Services/SystemHealth/WebServerMonitor.cs +++ b/DNN Platform/Library/Services/SystemHealth/WebServerMonitor.cs @@ -1,105 +1,109 @@ -namespace DotNetNuke.Services.SystemHealth -{ - using System; - using System.Linq; - using DotNetNuke.Entities.Host; - using DotNetNuke.Instrumentation; - using DotNetNuke.Services.Exceptions; - using DotNetNuke.Services.Scheduling; - - /// - /// When run on each server it updates the last activity date for the server and removes any servers that havent been seen in 24 hours. - /// - public class WebServerMonitor : SchedulerClient - { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(WebServerMonitor)); - - /// - /// Initializes a new instance of the class. - /// Constructs a WebServerMonitor SchedulerClient. - /// - /// A SchedulerHistiryItem. - /// - /// This must be run on all servers. - /// - public WebServerMonitor(ScheduleHistoryItem objScheduleHistoryItem) - { - this.ScheduleHistoryItem = objScheduleHistoryItem; - } - - /// - /// Runs on the active server and updates the last activity date for the current server. - /// - public override void DoWork() - { - try - { - Logger.Info("Starting WebServerMonitor"); - - this.UpdateCurrentServerActivity(); - this.DisableServersWithoutRecentActivity(); - this.RemoveInActiveServers(); - - Logger.Info("Finished WebServerMonitor"); - this.ScheduleHistoryItem.Succeeded = true; - } - catch (Exception exc) - { - this.ScheduleHistoryItem.Succeeded = false; - this.ScheduleHistoryItem.AddLogNote(string.Format("Updating server health failed: {0}.", exc.ToString())); - this.Errored(ref exc); - Logger.ErrorFormat("Error in WebServerMonitor: {0}. {1}", exc.Message, exc.StackTrace); - Exceptions.LogException(exc); - } - } - - private void UpdateCurrentServerActivity() - { - Logger.Info("Starting UpdateCurrentServerActivity"); - - // Creating a new ServerInfo object, by default points it at the current server - var currentServer = new ServerInfo(); - ServerController.UpdateServerActivity(currentServer); - - Logger.Info("Finished UpdateCurrentServerActivity"); - } - - private void DisableServersWithoutRecentActivity() - { - var serversWithActivity = ServerController.GetEnabledServersWithActivity(); - var newServer = serversWithActivity.FirstOrDefault(); - - foreach (var s in ServerController.GetInActiveServers(10)) - { - s.Enabled = false; - ServerController.UpdateServerActivity(s); - - // Update the schedules that were running on that server, that may never have been loaded - if (newServer != null) - { - SchedulingController.ReplaceServer(s, newServer); - } - } - } - - private void RemoveInActiveServers() - { - Logger.Info("Starting RemoveInActiveServers"); - var serversWithActivity = ServerController.GetEnabledServersWithActivity(); - var newServer = serversWithActivity.FirstOrDefault(); - - foreach (var s in ServerController.GetInActiveServers(1440)) - { - ServerController.DeleteServer(s.ServerID); - - // Update the schedules that were running on that server, that may never have been loaded - if (newServer != null) - { - SchedulingController.ReplaceServer(s, newServer); - } - } - - Logger.Info("Finished RemoveInActiveServers"); - } - } -} +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information +namespace DotNetNuke.Services.SystemHealth +{ + using System; + using System.Linq; + + using DotNetNuke.Entities.Host; + using DotNetNuke.Instrumentation; + using DotNetNuke.Services.Exceptions; + using DotNetNuke.Services.Scheduling; + + /// + /// When run on each server it updates the last activity date for the server and removes any servers that havent been seen in 24 hours. + /// + public class WebServerMonitor : SchedulerClient + { + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(WebServerMonitor)); + + /// + /// Initializes a new instance of the class. + /// Constructs a WebServerMonitor SchedulerClient. + /// + /// A SchedulerHistiryItem. + /// + /// This must be run on all servers. + /// + public WebServerMonitor(ScheduleHistoryItem objScheduleHistoryItem) + { + this.ScheduleHistoryItem = objScheduleHistoryItem; + } + + /// + /// Runs on the active server and updates the last activity date for the current server. + /// + public override void DoWork() + { + try + { + Logger.Info("Starting WebServerMonitor"); + + this.UpdateCurrentServerActivity(); + this.DisableServersWithoutRecentActivity(); + this.RemoveInActiveServers(); + + Logger.Info("Finished WebServerMonitor"); + this.ScheduleHistoryItem.Succeeded = true; + } + catch (Exception exc) + { + this.ScheduleHistoryItem.Succeeded = false; + this.ScheduleHistoryItem.AddLogNote(string.Format("Updating server health failed: {0}.", exc.ToString())); + this.Errored(ref exc); + Logger.ErrorFormat("Error in WebServerMonitor: {0}. {1}", exc.Message, exc.StackTrace); + Exceptions.LogException(exc); + } + } + + private void UpdateCurrentServerActivity() + { + Logger.Info("Starting UpdateCurrentServerActivity"); + + // Creating a new ServerInfo object, by default points it at the current server + var currentServer = new ServerInfo(); + ServerController.UpdateServerActivity(currentServer); + + Logger.Info("Finished UpdateCurrentServerActivity"); + } + + private void DisableServersWithoutRecentActivity() + { + var serversWithActivity = ServerController.GetEnabledServersWithActivity(); + var newServer = serversWithActivity.FirstOrDefault(); + + foreach (var s in ServerController.GetInActiveServers(10)) + { + s.Enabled = false; + ServerController.UpdateServerActivity(s); + + // Update the schedules that were running on that server, that may never have been loaded + if (newServer != null) + { + SchedulingController.ReplaceServer(s, newServer); + } + } + } + + private void RemoveInActiveServers() + { + Logger.Info("Starting RemoveInActiveServers"); + var serversWithActivity = ServerController.GetEnabledServersWithActivity(); + var newServer = serversWithActivity.FirstOrDefault(); + + foreach (var s in ServerController.GetInActiveServers(1440)) + { + ServerController.DeleteServer(s.ServerID); + + // Update the schedules that were running on that server, that may never have been loaded + if (newServer != null) + { + SchedulingController.ReplaceServer(s, newServer); + } + } + + Logger.Info("Finished RemoveInActiveServers"); + } + } +} diff --git a/DNN Platform/Library/Services/Upgrade/Upgrade.cs b/DNN Platform/Library/Services/Upgrade/Upgrade.cs index 6c1354d429e..2c04a82180a 100644 --- a/DNN Platform/Library/Services/Upgrade/Upgrade.cs +++ b/DNN Platform/Library/Services/Upgrade/Upgrade.cs @@ -31,6 +31,7 @@ namespace DotNetNuke.Services.Upgrade using DotNetNuke.Entities.Users; using DotNetNuke.Framework; using DotNetNuke.Instrumentation; + using DotNetNuke.Internal.SourceGenerators; using DotNetNuke.Security; using DotNetNuke.Security.Permissions; using DotNetNuke.Services.FileSystem; @@ -50,7 +51,7 @@ namespace DotNetNuke.Services.Upgrade using ModuleInfo = DotNetNuke.Entities.Modules.ModuleInfo; /// The Upgrade class provides Shared/Static methods to Upgrade/Install a DotNetNuke Application. - public class Upgrade + public partial class Upgrade { private const string FipsCompilanceAssembliesCheckedKey = "FipsCompilanceAssembliesChecked"; private const string FipsCompilanceAssembliesFolder = "App_Data\\FipsCompilanceAssemblies"; @@ -485,8 +486,8 @@ public static int AddPortal(XmlNode node, bool status, int indent, UserInfo supe /// Obsolete, AddPortal manages the Installation of a new DotNetNuke Portal. /// The ID of the new portal, or -1 to indicate failure. - [Obsolete("Deprecated in DNN 9.3.0, will be removed in 11.0.0. Use the overloaded method with the 'superUser' parameter instead. Scheduled removal in v11.0.0.")] - public static int AddPortal(XmlNode node, bool status, int indent) + [DnnDeprecated(9, 3, 0, "Use the overloaded method with the 'superUser' parameter instead")] + public static partial int AddPortal(XmlNode node, bool status, int indent) { return AddPortal(node, status, indent, null); } diff --git a/DNN Platform/Library/Services/Url/FriendlyUrl/FriendlyUrlProvider.cs b/DNN Platform/Library/Services/Url/FriendlyUrl/FriendlyUrlProvider.cs index d0a966af1fc..5b251d1fa4d 100644 --- a/DNN Platform/Library/Services/Url/FriendlyUrl/FriendlyUrlProvider.cs +++ b/DNN Platform/Library/Services/Url/FriendlyUrl/FriendlyUrlProvider.cs @@ -9,8 +9,9 @@ namespace DotNetNuke.Services.Url.FriendlyUrl using DotNetNuke.ComponentModel; using DotNetNuke.Entities.Portals; using DotNetNuke.Entities.Tabs; + using DotNetNuke.Internal.SourceGenerators; - public abstract class FriendlyUrlProvider + public abstract partial class FriendlyUrlProvider { // return the provider public static FriendlyUrlProvider Instance() @@ -22,8 +23,8 @@ public static FriendlyUrlProvider Instance() public abstract string FriendlyUrl(TabInfo tab, string path, string pageName); - [Obsolete("Deprecated in Platform 9.4.3. Scheduled for removal in v11.0.0. Use the IPortalSettings overload")] - public virtual string FriendlyUrl(TabInfo tab, string path, string pageName, PortalSettings settings) + [DnnDeprecated(9, 4, 3, "Use the IPortalSettings overload")] + public virtual partial string FriendlyUrl(TabInfo tab, string path, string pageName, PortalSettings settings) { return this.FriendlyUrl(tab, path, pageName, (IPortalSettings)settings); } diff --git a/DNN Platform/Library/Startup.cs b/DNN Platform/Library/Startup.cs index 1dda82c3953..f3702af3786 100644 --- a/DNN Platform/Library/Startup.cs +++ b/DNN Platform/Library/Startup.cs @@ -4,6 +4,7 @@ namespace DotNetNuke { using System; + using DotNetNuke.Abstractions; using DotNetNuke.Abstractions.Application; using DotNetNuke.Abstractions.Logging; @@ -16,6 +17,7 @@ namespace DotNetNuke using DotNetNuke.Entities.Modules.Settings; using DotNetNuke.Entities.Portals; using DotNetNuke.Services.Log.EventLog; + using DotNetNuke.Services.Mail.OAuth; using DotNetNuke.UI.Modules; using DotNetNuke.UI.Modules.Html5; @@ -49,6 +51,8 @@ public void ConfigureServices(IServiceCollection services) services.AddScoped(); services.AddTransient(); + services.AddTransient(); + SmtpOAuthController.RegisterOAuthProviders(services); } } } diff --git a/DNN Platform/Library/UI/Containers/ActionBase.cs b/DNN Platform/Library/UI/Containers/ActionBase.cs index a9c3311932c..719e5b602b1 100644 --- a/DNN Platform/Library/UI/Containers/ActionBase.cs +++ b/DNN Platform/Library/UI/Containers/ActionBase.cs @@ -21,7 +21,7 @@ namespace DotNetNuke.UI.Containers public abstract class ActionBase : UserControl, IActionControl { /// Defines if the action supports icons. - [Obsolete("Deprecates in v9.8.1, sheduled removal in v11.")] + [Obsolete("Deprecated in DotNetNuke 9.8.1. Use SupportsIcons property. Scheduled for removal in v11.0.0.")] [System.Diagnostics.CodeAnalysis.SuppressMessage( "StyleCop.CSharp.NamingRules", "SA1308:Variable names should not be prefixed", diff --git a/DNN Platform/Library/UI/Containers/ActionButton.cs b/DNN Platform/Library/UI/Containers/ActionButton.cs index 50b0bbb9afa..a1b481e22fc 100644 --- a/DNN Platform/Library/UI/Containers/ActionButton.cs +++ b/DNN Platform/Library/UI/Containers/ActionButton.cs @@ -3,9 +3,8 @@ // See the LICENSE file in the project root for more information namespace DotNetNuke.UI.Containers { - using System; - using DotNetNuke.Entities.Modules.Actions; + using DotNetNuke.Internal.SourceGenerators; /// Project : DotNetNuke /// Namespace: DotNetNuke.UI.Containers @@ -14,8 +13,8 @@ namespace DotNetNuke.UI.Containers /// /// ActionBase inherits from UserControl, and implements the IActionControl Interface. /// - [Obsolete("This class has been deprecated in favour of the new ActionCommandButton and ActionButtonList.. Scheduled removal in v11.0.0.")] - public class ActionButton : ActionBase + [DnnDeprecated(7, 0, 0, "This class has been deprecated in favour of the new ActionCommandButton and ActionButtonList", RemovalVersion = 11)] + public partial class ActionButton : ActionBase { private ActionButtonList buttonList; diff --git a/DNN Platform/Library/UI/Modules/ModuleControlFactory.cs b/DNN Platform/Library/UI/Modules/ModuleControlFactory.cs index 1c80c0a07fa..82aa97917cd 100644 --- a/DNN Platform/Library/UI/Modules/ModuleControlFactory.cs +++ b/DNN Platform/Library/UI/Modules/ModuleControlFactory.cs @@ -2,216 +2,217 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information -namespace DotNetNuke.UI.Modules -{ - using System; - using System.IO; - using System.Web.UI; - - using DotNetNuke.Entities.Modules; - using DotNetNuke.Framework; - using DotNetNuke.Instrumentation; - using DotNetNuke.Services.Localization; - using DotNetNuke.UI.Modules.Html5; - - [Obsolete("This implementation has moved to DotNetNuke.ModulePipeline.ModuleControlFactory. Scheduled removal in v11.0.0.")] - public class ModuleControlFactory - { - private static readonly ILog TracelLogger = LoggerSource.Instance.GetLogger("DNN.Trace"); - - [Obsolete("This implementation has moved to DotNetNuke.ModulePipeline.ModuleControlFactory. Scheduled removal in v11.0.0.")] - public static Control LoadModuleControl(TemplateControl containerControl, ModuleInfo moduleConfiguration, string controlKey, string controlSrc) - { - if (TracelLogger.IsDebugEnabled) - { - TracelLogger.Debug($"ModuleControlFactory.LoadModuleControl Start (TabId:{moduleConfiguration.TabID},ModuleId:{moduleConfiguration.ModuleID}): ModuleControlSource:{moduleConfiguration.ModuleControl.ControlSrc}"); - } - - Control control = null; - IModuleControlFactory controlFactory = GetModuleControlFactory(controlSrc); - - if (controlFactory != null) - { - control = controlFactory.CreateControl(containerControl, controlKey, controlSrc); - } - - // set the control ID to the resource file name ( ie. controlname.ascx = controlname ) - // this is necessary for the Localization in PageBase - if (control != null) - { - control.ID = Path.GetFileNameWithoutExtension(controlSrc); - - var moduleControl = control as IModuleControl; - - if (moduleControl != null) - { - moduleControl.ModuleContext.Configuration = moduleConfiguration; - } - } - - if (TracelLogger.IsDebugEnabled) - { - TracelLogger.Debug($"ModuleControlFactory.LoadModuleControl End (TabId:{moduleConfiguration.TabID},ModuleId:{moduleConfiguration.ModuleID}): ModuleControlSource:{moduleConfiguration.ModuleControl.ControlSrc}"); - } - - return control; - } - - [Obsolete("This implementation has moved to DotNetNuke.ModulePipeline.ModuleControlFactory. Scheduled removal in v11.0.0.")] - public static Control LoadModuleControl(TemplateControl containerControl, ModuleInfo moduleConfiguration) - { - if (TracelLogger.IsDebugEnabled) - { - TracelLogger.Debug($"ModuleControlFactory.LoadModuleControl Start (TabId:{moduleConfiguration.TabID},ModuleId:{moduleConfiguration.ModuleID}): ModuleControlSource:{moduleConfiguration.ModuleControl.ControlSrc}"); - } - - Control control = null; - IModuleControlFactory controlFactory = GetModuleControlFactory(moduleConfiguration.ModuleControl.ControlSrc); - - if (controlFactory != null) - { - control = controlFactory.CreateModuleControl(containerControl, moduleConfiguration); - } - - // set the control ID to the resource file name ( ie. controlname.ascx = controlname ) - // this is necessary for the Localization in PageBase - if (control != null) - { - control.ID = Path.GetFileNameWithoutExtension(moduleConfiguration.ModuleControl.ControlSrc); - - var moduleControl = control as IModuleControl; - - if (moduleControl != null) - { - moduleControl.ModuleContext.Configuration = moduleConfiguration; - } - } - - if (TracelLogger.IsDebugEnabled) - { - TracelLogger.Debug($"ModuleControlFactory.LoadModuleControl End (TabId:{moduleConfiguration.TabID},ModuleId:{moduleConfiguration.ModuleID}): ModuleControlSource:{moduleConfiguration.ModuleControl.ControlSrc}"); - } - - return control; - } - - [Obsolete("This implementation has moved to DotNetNuke.ModulePipeline.ModuleControlFactory. Scheduled removal in v11.0.0.")] - public static Control LoadSettingsControl(TemplateControl containerControl, ModuleInfo moduleConfiguration, string controlSrc) - { - if (TracelLogger.IsDebugEnabled) - { - TracelLogger.Debug($"ModuleControlFactory.LoadSettingsControl Start (TabId:{moduleConfiguration.TabID},ModuleId:{moduleConfiguration.ModuleID}): ModuleControlSource:{moduleConfiguration.ModuleControl.ControlSrc}"); - } - - Control control = null; - IModuleControlFactory controlFactory = GetModuleControlFactory(controlSrc); - - if (controlFactory != null) - { - control = controlFactory.CreateSettingsControl(containerControl, moduleConfiguration, controlSrc); - } - - // set the control ID to the resource file name ( ie. controlname.ascx = controlname ) - // this is necessary for the Localization in PageBase - if (control != null) - { - var fileNameWithoutExtension = Path.GetFileNameWithoutExtension(controlSrc); - if (fileNameWithoutExtension != null) - { - control.ID = fileNameWithoutExtension.Replace('.', '-'); - } - - var settingsControl = control as ISettingsControl; - - if (settingsControl != null) - { - settingsControl.ModuleContext.Configuration = moduleConfiguration; - } - } - - if (TracelLogger.IsDebugEnabled) - { - TracelLogger.Debug($"ModuleControlFactory.LoadSettingsControl End (TabId:{moduleConfiguration.TabID},ModuleId:{moduleConfiguration.ModuleID}): ModuleControlSource:{moduleConfiguration.ModuleControl.ControlSrc}"); - } - - return control; - } - - [Obsolete("This implementation has moved to DotNetNuke.ModulePipeline.ModuleControlFactory. Scheduled removal in v11.0.0.")] - public static Control CreateCachedControl(string cachedContent, ModuleInfo moduleConfiguration) - { - var moduleControl = new CachedModuleControl(cachedContent); - moduleControl.ModuleContext.Configuration = moduleConfiguration; - return moduleControl; - } - - [Obsolete("This implementation has moved to DotNetNuke.ModulePipeline.ModuleControlFactory. Scheduled removal in v11.0.0.")] - public static Control CreateModuleControl(ModuleInfo moduleConfiguration) - { - string extension = Path.GetExtension(moduleConfiguration.ModuleControl.ControlSrc.ToLowerInvariant()); - var moduleControl = new ModuleControlBase(); - moduleControl.ModuleContext.Configuration = moduleConfiguration; - - switch (extension) - { - case ".mvc": - var segments = moduleConfiguration.ModuleControl.ControlSrc.Replace(".mvc", string.Empty).Split('/'); - - moduleControl.LocalResourceFile = string.Format( - "~/DesktopModules/MVC/{0}/{1}/{2}.resx", - moduleConfiguration.DesktopModule.FolderName, - Localization.LocalResourceDirectory, - segments[0]); - break; - default: - moduleControl.LocalResourceFile = moduleConfiguration.ModuleControl.ControlSrc.Replace(Path.GetFileName(moduleConfiguration.ModuleControl.ControlSrc), string.Empty) + - Localization.LocalResourceDirectory + "/" + - Path.GetFileName(moduleConfiguration.ModuleControl.ControlSrc); - break; - } - - return moduleControl; - } - - [Obsolete("This implementation has moved to DotNetNuke.ModulePipeline.ModuleControlFactory. Scheduled removal in v11.0.0.")] - private static IModuleControlFactory GetModuleControlFactory(string controlSrc) - { - string extension = Path.GetExtension(controlSrc.ToLowerInvariant()); - - IModuleControlFactory controlFactory = null; - Type factoryType; - switch (extension) - { - case ".ascx": - controlFactory = new WebFormsModuleControlFactory(); - break; - case ".html": - case ".htm": - controlFactory = new Html5ModuleControlFactory(); - break; - case ".cshtml": - case ".vbhtml": - factoryType = Reflection.CreateType("DotNetNuke.Web.Razor.RazorModuleControlFactory"); - if (factoryType != null) - { - controlFactory = Reflection.CreateObject(factoryType) as IModuleControlFactory; - } - - break; - case ".mvc": - factoryType = Reflection.CreateType("DotNetNuke.Web.Mvc.MvcModuleControlFactory"); - if (factoryType != null) - { - controlFactory = Reflection.CreateObject(factoryType) as IModuleControlFactory; - } - - break; - default: - controlFactory = new ReflectedModuleControlFactory(); - break; - } - - return controlFactory; - } - } -} +namespace DotNetNuke.UI.Modules +{ + using System; + using System.IO; + using System.Web.UI; + + using DotNetNuke.Entities.Modules; + using DotNetNuke.Framework; + using DotNetNuke.Instrumentation; + using DotNetNuke.Internal.SourceGenerators; + using DotNetNuke.Services.Localization; + using DotNetNuke.UI.Modules.Html5; + + [DnnDeprecated(9, 4, 0, "This implementation has moved to DotNetNuke.ModulePipeline.ModuleControlFactory")] + public partial class ModuleControlFactory + { + private static readonly ILog TracelLogger = LoggerSource.Instance.GetLogger("DNN.Trace"); + + [DnnDeprecated(9, 4, 0, "This implementation has moved to DotNetNuke.ModulePipeline.ModuleControlFactory")] + public static partial Control LoadModuleControl(TemplateControl containerControl, ModuleInfo moduleConfiguration, string controlKey, string controlSrc) + { + if (TracelLogger.IsDebugEnabled) + { + TracelLogger.Debug($"ModuleControlFactory.LoadModuleControl Start (TabId:{moduleConfiguration.TabID},ModuleId:{moduleConfiguration.ModuleID}): ModuleControlSource:{moduleConfiguration.ModuleControl.ControlSrc}"); + } + + Control control = null; + IModuleControlFactory controlFactory = GetModuleControlFactory(controlSrc); + + if (controlFactory != null) + { + control = controlFactory.CreateControl(containerControl, controlKey, controlSrc); + } + + // set the control ID to the resource file name ( ie. controlname.ascx = controlname ) + // this is necessary for the Localization in PageBase + if (control != null) + { + control.ID = Path.GetFileNameWithoutExtension(controlSrc); + + var moduleControl = control as IModuleControl; + + if (moduleControl != null) + { + moduleControl.ModuleContext.Configuration = moduleConfiguration; + } + } + + if (TracelLogger.IsDebugEnabled) + { + TracelLogger.Debug($"ModuleControlFactory.LoadModuleControl End (TabId:{moduleConfiguration.TabID},ModuleId:{moduleConfiguration.ModuleID}): ModuleControlSource:{moduleConfiguration.ModuleControl.ControlSrc}"); + } + + return control; + } + + [DnnDeprecated(9, 4, 0, "This implementation has moved to DotNetNuke.ModulePipeline.ModuleControlFactory")] + public static partial Control LoadModuleControl(TemplateControl containerControl, ModuleInfo moduleConfiguration) + { + if (TracelLogger.IsDebugEnabled) + { + TracelLogger.Debug($"ModuleControlFactory.LoadModuleControl Start (TabId:{moduleConfiguration.TabID},ModuleId:{moduleConfiguration.ModuleID}): ModuleControlSource:{moduleConfiguration.ModuleControl.ControlSrc}"); + } + + Control control = null; + IModuleControlFactory controlFactory = GetModuleControlFactory(moduleConfiguration.ModuleControl.ControlSrc); + + if (controlFactory != null) + { + control = controlFactory.CreateModuleControl(containerControl, moduleConfiguration); + } + + // set the control ID to the resource file name ( ie. controlname.ascx = controlname ) + // this is necessary for the Localization in PageBase + if (control != null) + { + control.ID = Path.GetFileNameWithoutExtension(moduleConfiguration.ModuleControl.ControlSrc); + + var moduleControl = control as IModuleControl; + + if (moduleControl != null) + { + moduleControl.ModuleContext.Configuration = moduleConfiguration; + } + } + + if (TracelLogger.IsDebugEnabled) + { + TracelLogger.Debug($"ModuleControlFactory.LoadModuleControl End (TabId:{moduleConfiguration.TabID},ModuleId:{moduleConfiguration.ModuleID}): ModuleControlSource:{moduleConfiguration.ModuleControl.ControlSrc}"); + } + + return control; + } + + [DnnDeprecated(9, 4, 0, "This implementation has moved to DotNetNuke.ModulePipeline.ModuleControlFactory")] + public static partial Control LoadSettingsControl(TemplateControl containerControl, ModuleInfo moduleConfiguration, string controlSrc) + { + if (TracelLogger.IsDebugEnabled) + { + TracelLogger.Debug($"ModuleControlFactory.LoadSettingsControl Start (TabId:{moduleConfiguration.TabID},ModuleId:{moduleConfiguration.ModuleID}): ModuleControlSource:{moduleConfiguration.ModuleControl.ControlSrc}"); + } + + Control control = null; + IModuleControlFactory controlFactory = GetModuleControlFactory(controlSrc); + + if (controlFactory != null) + { + control = controlFactory.CreateSettingsControl(containerControl, moduleConfiguration, controlSrc); + } + + // set the control ID to the resource file name ( ie. controlname.ascx = controlname ) + // this is necessary for the Localization in PageBase + if (control != null) + { + var fileNameWithoutExtension = Path.GetFileNameWithoutExtension(controlSrc); + if (fileNameWithoutExtension != null) + { + control.ID = fileNameWithoutExtension.Replace('.', '-'); + } + + var settingsControl = control as ISettingsControl; + + if (settingsControl != null) + { + settingsControl.ModuleContext.Configuration = moduleConfiguration; + } + } + + if (TracelLogger.IsDebugEnabled) + { + TracelLogger.Debug($"ModuleControlFactory.LoadSettingsControl End (TabId:{moduleConfiguration.TabID},ModuleId:{moduleConfiguration.ModuleID}): ModuleControlSource:{moduleConfiguration.ModuleControl.ControlSrc}"); + } + + return control; + } + + [DnnDeprecated(9, 4, 0, "This implementation has moved to DotNetNuke.ModulePipeline.ModuleControlFactory")] + public static partial Control CreateCachedControl(string cachedContent, ModuleInfo moduleConfiguration) + { + var moduleControl = new CachedModuleControl(cachedContent); + moduleControl.ModuleContext.Configuration = moduleConfiguration; + return moduleControl; + } + + [DnnDeprecated(9, 4, 0, "This implementation has moved to DotNetNuke.ModulePipeline.ModuleControlFactory")] + public static partial Control CreateModuleControl(ModuleInfo moduleConfiguration) + { + string extension = Path.GetExtension(moduleConfiguration.ModuleControl.ControlSrc.ToLowerInvariant()); + var moduleControl = new ModuleControlBase(); + moduleControl.ModuleContext.Configuration = moduleConfiguration; + + switch (extension) + { + case ".mvc": + var segments = moduleConfiguration.ModuleControl.ControlSrc.Replace(".mvc", string.Empty).Split('/'); + + moduleControl.LocalResourceFile = string.Format( + "~/DesktopModules/MVC/{0}/{1}/{2}.resx", + moduleConfiguration.DesktopModule.FolderName, + Localization.LocalResourceDirectory, + segments[0]); + break; + default: + moduleControl.LocalResourceFile = moduleConfiguration.ModuleControl.ControlSrc.Replace(Path.GetFileName(moduleConfiguration.ModuleControl.ControlSrc), string.Empty) + + Localization.LocalResourceDirectory + "/" + + Path.GetFileName(moduleConfiguration.ModuleControl.ControlSrc); + break; + } + + return moduleControl; + } + + [DnnDeprecated(9, 4, 0, "This implementation has moved to DotNetNuke.ModulePipeline.ModuleControlFactory")] + private static partial IModuleControlFactory GetModuleControlFactory(string controlSrc) + { + string extension = Path.GetExtension(controlSrc.ToLowerInvariant()); + + IModuleControlFactory controlFactory = null; + Type factoryType; + switch (extension) + { + case ".ascx": + controlFactory = new WebFormsModuleControlFactory(); + break; + case ".html": + case ".htm": + controlFactory = new Html5ModuleControlFactory(); + break; + case ".cshtml": + case ".vbhtml": + factoryType = Reflection.CreateType("DotNetNuke.Web.Razor.RazorModuleControlFactory"); + if (factoryType != null) + { + controlFactory = Reflection.CreateObject(factoryType) as IModuleControlFactory; + } + + break; + case ".mvc": + factoryType = Reflection.CreateType("DotNetNuke.Web.Mvc.MvcModuleControlFactory"); + if (factoryType != null) + { + controlFactory = Reflection.CreateObject(factoryType) as IModuleControlFactory; + } + + break; + default: + controlFactory = new ReflectedModuleControlFactory(); + break; + } + + return controlFactory; + } + } +} diff --git a/DNN Platform/Library/UI/Utilities/DNNClientAPI.cs b/DNN Platform/Library/UI/Utilities/DNNClientAPI.cs index 4cf78d812e9..037288263e9 100644 --- a/DNN Platform/Library/UI/Utilities/DNNClientAPI.cs +++ b/DNN Platform/Library/UI/Utilities/DNNClientAPI.cs @@ -13,6 +13,7 @@ namespace DotNetNuke.UI.Utilities using DotNetNuke.Common.Utilities; using DotNetNuke.Entities.Portals; using DotNetNuke.Framework.JavaScriptLibraries; + using DotNetNuke.Internal.SourceGenerators; using DotNetNuke.Services.Localization; using DotNetNuke.Services.Personalization; @@ -20,7 +21,7 @@ namespace DotNetNuke.UI.Utilities /// Class : ClientAPI /// /// Library responsible for interacting with DNN Client API. - public class DNNClientAPI + public partial class DNNClientAPI { private static readonly Hashtable ObjEnabledClientPersonalizationKeys = new Hashtable(); @@ -41,8 +42,8 @@ public enum PageCallBackType /// Adds client side body.onload event handler. /// Current page rendering content. /// Javascript function name to execute. - [Obsolete("This method has been deprecated and its code replaced in the 7.1.0 release. Scheduled removal in v10.0.0.")] - public static void AddBodyOnloadEventHandler(Page objPage, string strJSFunction) + [DnnDeprecated(7, 1, 0, "No replacement")] + public static partial void AddBodyOnloadEventHandler(Page objPage, string strJSFunction) { // legacy implementation replaced AddBodyOnLoad(objPage, strJSFunction, strJSFunction); diff --git a/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/DNN Edit Controls/DNNListEditControl.cs b/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/DNN Edit Controls/DNNListEditControl.cs index d8669f33305..a32d138128a 100644 --- a/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/DNN Edit Controls/DNNListEditControl.cs +++ b/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/DNN Edit Controls/DNNListEditControl.cs @@ -1,406 +1,406 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information -namespace DotNetNuke.UI.WebControls -{ - using System; - using System.Collections.Generic; - using System.ComponentModel; - using System.Linq; - using System.Web; - using System.Web.UI; - - using DotNetNuke.Common.Lists; - using DotNetNuke.Common.Utilities; - using DotNetNuke.Entities.Portals; - using DotNetNuke.Instrumentation; +namespace DotNetNuke.UI.WebControls +{ + using System; + using System.Collections.Generic; + using System.ComponentModel; + using System.Linq; + using System.Web; + using System.Web.UI; + + using DotNetNuke.Common.Lists; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Instrumentation; using DotNetNuke.Services.Localization; - /// Project: DotNetNuke - /// Namespace: DotNetNuke.UI.WebControls - /// Class: DNNListEditControl - /// - /// The DNNListEditControl control provides a standard UI component for selecting - /// from Lists. - /// - [ToolboxData("<{0}:DNNListEditControl runat=server>")] - public class DNNListEditControl : EditControl, IPostBackEventHandler - { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(DNNListEditControl)); - private List listEntries; + /// Project: DotNetNuke + /// Namespace: DotNetNuke.UI.WebControls + /// Class: DNNListEditControl + /// + /// The DNNListEditControl control provides a standard UI component for selecting + /// from Lists. + /// + [ToolboxData("<{0}:DNNListEditControl runat=server>")] + public class DNNListEditControl : EditControl, IPostBackEventHandler + { + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(DNNListEditControl)); + private List listEntries; private string listName = string.Empty; /// Initializes a new instance of the class. - public DNNListEditControl() - { - this.ValueField = ListBoundField.Value; - this.TextField = ListBoundField.Text; - this.ParentKey = string.Empty; - this.SortAlphabetically = false; - } - - public event PropertyChangedEventHandler ItemChanged; - - /// Gets integerValue returns the Integer representation of the Value. - /// An integer representing the Value. - protected int IntegerValue - { - get - { - int intValue = Null.NullInteger; - if (this.Value == null || string.IsNullOrEmpty((string)this.Value)) - { - return intValue; - } - - try - { - intValue = Convert.ToInt32(this.Value); - } - catch (Exception exc) - { - Logger.Error(exc); - } - - return intValue; - } - } - - /// Gets list gets the List associated with the control. - [Obsolete("Obsoleted in 6.0.1 use ListEntries instead. Scheduled removal in v10.0.0.")] - [EditorBrowsable(EditorBrowsableState.Never)] - protected ListEntryInfoCollection List - { - get - { - var listController = new ListController(); - return listController.GetListEntryInfoCollection(this.ListName, this.ParentKey, this.PortalId); - } + public DNNListEditControl() + { + this.ValueField = ListBoundField.Value; + this.TextField = ListBoundField.Text; + this.ParentKey = string.Empty; + this.SortAlphabetically = false; + } + + public event PropertyChangedEventHandler ItemChanged; + + /// Gets integerValue returns the Integer representation of the Value. + /// An integer representing the Value. + protected int IntegerValue + { + get + { + int intValue = Null.NullInteger; + if (this.Value == null || string.IsNullOrEmpty((string)this.Value)) + { + return intValue; + } + + try + { + intValue = Convert.ToInt32(this.Value); + } + catch (Exception exc) + { + Logger.Error(exc); + } + + return intValue; + } + } + + /// Gets list gets the List associated with the control. + [Obsolete("Deprecated in DotNetNuke 6.0.1. Use ListEntries instead. Scheduled for removal in v10.0.0.")] + [EditorBrowsable(EditorBrowsableState.Never)] + protected ListEntryInfoCollection List + { + get + { + var listController = new ListController(); + return listController.GetListEntryInfoCollection(this.ListName, this.ParentKey, this.PortalId); + } + } + + /// Gets the ListEntryInfo objects associated witht the control. + protected IEnumerable ListEntries + { + get + { + if (this.listEntries == null) + { + var listController = new ListController(); + if (this.SortAlphabetically) + { + this.listEntries = listController.GetListEntryInfoItems(this.ListName, this.ParentKey, this.PortalId).OrderBy(s => s.SortOrder).ThenBy(s => s.Text).ToList(); + } + else + { + this.listEntries = listController.GetListEntryInfoItems(this.ListName, this.ParentKey, this.PortalId).ToList(); + } + } + + return this.listEntries; + } + } + + /// Gets oldIntegerValue returns the Integer representation of the OldValue. + /// An integer representing the OldValue. + protected int OldIntegerValue + { + get + { + int intValue = Null.NullInteger; + if (this.OldValue == null || string.IsNullOrEmpty(this.OldValue.ToString())) + { + return intValue; + } + + try + { + // Try and cast the value to an Integer + intValue = Convert.ToInt32(this.OldValue); + } + catch (Exception exc) + { + Logger.Error(exc); + } + + return intValue; + } + } + + protected int PortalId + { + get + { + return PortalController.GetEffectivePortalId(PortalSettings.Current.PortalId); + } } - /// Gets the ListEntryInfo objects associated witht the control. - protected IEnumerable ListEntries - { - get - { - if (this.listEntries == null) - { - var listController = new ListController(); - if (this.SortAlphabetically) - { - this.listEntries = listController.GetListEntryInfoItems(this.ListName, this.ParentKey, this.PortalId).OrderBy(s => s.SortOrder).ThenBy(s => s.Text).ToList(); - } - else - { - this.listEntries = listController.GetListEntryInfoItems(this.ListName, this.ParentKey, this.PortalId).ToList(); - } - } - - return this.listEntries; - } - } - - /// Gets oldIntegerValue returns the Integer representation of the OldValue. - /// An integer representing the OldValue. - protected int OldIntegerValue - { - get - { - int intValue = Null.NullInteger; - if (this.OldValue == null || string.IsNullOrEmpty(this.OldValue.ToString())) - { - return intValue; - } - - try - { - // Try and cast the value to an Integer - intValue = Convert.ToInt32(this.OldValue); - } - catch (Exception exc) - { - Logger.Error(exc); - } - - return intValue; - } - } - - protected int PortalId - { - get - { - return PortalController.GetEffectivePortalId(PortalSettings.Current.PortalId); - } - } - - /// Gets oldStringValue returns the Boolean representation of the OldValue. - /// A String representing the OldValue. - protected string OldStringValue - { - get - { - return Convert.ToString(this.OldValue); - } - } - - /// Gets or sets a value indicating whether determines whether the List Auto Posts Back. - protected bool AutoPostBack { get; set; } - - /// Gets or sets a value indicating whether if true the list will be sorted on the value of Text before rendering. - protected bool SortAlphabetically { get; set; } - - /// Gets or sets listName is the name of the List to display. - protected virtual string ListName - { - get - { - if (this.listName == Null.NullString) - { - this.listName = this.DataField; - } - - return this.listName; - } - - set - { - this.listName = value; - } - } - - /// Gets or sets the parent key of the List to display. - protected virtual string ParentKey { get; set; } - - /// Gets or sets the field to display in the combo. - protected virtual ListBoundField TextField { get; set; } - - /// Gets or sets the field to use as the combo item values. - protected virtual ListBoundField ValueField { get; set; } - - /// Gets or sets stringValue is the value of the control expressed as a String. - /// A string representing the Value. - protected override string StringValue - { - get - { - return Convert.ToString(this.Value); - } - - set - { - if (this.ValueField == ListBoundField.Id) - { - // Integer type field - this.Value = int.Parse(value); - } - else - { - // String type Field - this.Value = value; - } - } + /// Gets oldStringValue returns the Boolean representation of the OldValue. + /// A String representing the OldValue. + protected string OldStringValue + { + get + { + return Convert.ToString(this.OldValue); + } + } + + /// Gets or sets a value indicating whether determines whether the List Auto Posts Back. + protected bool AutoPostBack { get; set; } + + /// Gets or sets a value indicating whether if true the list will be sorted on the value of Text before rendering. + protected bool SortAlphabetically { get; set; } + + /// Gets or sets listName is the name of the List to display. + protected virtual string ListName + { + get + { + if (this.listName == Null.NullString) + { + this.listName = this.DataField; + } + + return this.listName; + } + + set + { + this.listName = value; + } + } + + /// Gets or sets the parent key of the List to display. + protected virtual string ParentKey { get; set; } + + /// Gets or sets the field to display in the combo. + protected virtual ListBoundField TextField { get; set; } + + /// Gets or sets the field to use as the combo item values. + protected virtual ListBoundField ValueField { get; set; } + + /// Gets or sets stringValue is the value of the control expressed as a String. + /// A string representing the Value. + protected override string StringValue + { + get + { + return Convert.ToString(this.Value); + } + + set + { + if (this.ValueField == ListBoundField.Id) + { + // Integer type field + this.Value = int.Parse(value); + } + else + { + // String type Field + this.Value = value; + } + } } /// - public void RaisePostBackEvent(string eventArgument) - { - if (this.AutoPostBack) - { - this.OnItemChanged(this.GetEventArgs()); - } - } - - /// OnAttributesChanged runs when the CustomAttributes property has changed. - protected override void OnAttributesChanged() - { - // Get the List settings out of the "Attributes" - if (this.CustomAttributes != null) - { - foreach (Attribute attribute in this.CustomAttributes) - { - if (attribute is ListAttribute) - { - var listAtt = (ListAttribute)attribute; - this.ListName = listAtt.ListName; - this.ParentKey = listAtt.ParentKey; - this.TextField = listAtt.TextField; - this.ValueField = listAtt.ValueField; - break; - } - } - } - } - - /// - /// OnDataChanged runs when the PostbackData has changed. It raises the ValueChanged - /// Event. - /// - protected override void OnDataChanged(EventArgs e) - { - this.OnValueChanged(this.GetEventArgs()); - } - - /// OnItemChanged runs when the Item has changed. - protected virtual void OnItemChanged(PropertyEditorEventArgs e) - { - if (this.ItemChanged != null) - { - this.ItemChanged(this, e); - } + public void RaisePostBackEvent(string eventArgument) + { + if (this.AutoPostBack) + { + this.OnItemChanged(this.GetEventArgs()); + } + } + + /// OnAttributesChanged runs when the CustomAttributes property has changed. + protected override void OnAttributesChanged() + { + // Get the List settings out of the "Attributes" + if (this.CustomAttributes != null) + { + foreach (Attribute attribute in this.CustomAttributes) + { + if (attribute is ListAttribute) + { + var listAtt = (ListAttribute)attribute; + this.ListName = listAtt.ListName; + this.ParentKey = listAtt.ParentKey; + this.TextField = listAtt.TextField; + this.ValueField = listAtt.ValueField; + break; + } + } + } + } + + /// + /// OnDataChanged runs when the PostbackData has changed. It raises the ValueChanged + /// Event. + /// + protected override void OnDataChanged(EventArgs e) + { + this.OnValueChanged(this.GetEventArgs()); } - /// RenderViewMode renders the View (readonly) mode of the control. - /// A HtmlTextWriter. - protected override void RenderViewMode(HtmlTextWriter writer) - { - var objListController = new ListController(); - ListEntryInfo entry = null; - string entryText = Null.NullString; - switch (this.ValueField) - { - case ListBoundField.Id: - entry = objListController.GetListEntryInfo(this.ListName, Convert.ToInt32(this.Value)); - break; - case ListBoundField.Text: - entryText = this.StringValue; - break; - case ListBoundField.Value: - entry = objListController.GetListEntryInfo(this.ListName, this.StringValue); - break; - } - - this.ControlStyle.AddAttributesToRender(writer); - writer.RenderBeginTag(HtmlTextWriterTag.Span); - if (entry != null) - { - switch (this.TextField) - { - case ListBoundField.Id: - writer.Write(entry.EntryID.ToString()); - break; - case ListBoundField.Text: - writer.Write(entry.Text); - break; - case ListBoundField.Value: - writer.Write(entry.Value); - break; - } - } - else - { - writer.Write(entryText); - } - - // Close Select Tag - writer.RenderEndTag(); + /// OnItemChanged runs when the Item has changed. + protected virtual void OnItemChanged(PropertyEditorEventArgs e) + { + if (this.ItemChanged != null) + { + this.ItemChanged(this, e); + } } - /// RenderEditMode renders the Edit mode of the control. - /// A HtmlTextWriter. - protected override void RenderEditMode(HtmlTextWriter writer) - { - // Render the Select Tag - this.ControlStyle.AddAttributesToRender(writer); - writer.AddAttribute(HtmlTextWriterAttribute.Name, this.UniqueID); - writer.AddAttribute(HtmlTextWriterAttribute.Id, this.ClientID); - writer.AddAttribute("data-name", this.Name); - writer.AddAttribute("data-list", this.ListName); - writer.AddAttribute("data-category", this.Category); - writer.AddAttribute("data-editor", "DNNListEditControl"); - if (this.AutoPostBack) - { - writer.AddAttribute(HtmlTextWriterAttribute.Onchange, this.Page.ClientScript.GetPostBackEventReference(this, this.ID)); - } - - writer.RenderBeginTag(HtmlTextWriterTag.Select); - - // Add the Not Specified Option - if (this.ValueField == ListBoundField.Text) - { - writer.AddAttribute(HtmlTextWriterAttribute.Value, Null.NullString); - } - else - { - writer.AddAttribute(HtmlTextWriterAttribute.Value, Null.NullString); - } - - if (this.StringValue == Null.NullString) - { - // Add the Selected Attribute - writer.AddAttribute(HtmlTextWriterAttribute.Selected, "selected"); - } - - var defaultText = HttpUtility.HtmlEncode("<" + Localization.GetString("Not_Specified", Localization.SharedResourceFile) + ">"); - writer.RenderBeginTag(HtmlTextWriterTag.Option); - writer.Write(defaultText); - writer.RenderEndTag(); - - foreach (ListEntryInfo item in this.ListEntries) - { - string itemValue = Null.NullString; - - // Add the Value Attribute - switch (this.ValueField) - { - case ListBoundField.Id: - itemValue = item.EntryID.ToString(); - break; - case ListBoundField.Text: - itemValue = item.Text; - break; - case ListBoundField.Value: - itemValue = item.Value; - break; - } - - writer.AddAttribute(HtmlTextWriterAttribute.Value, itemValue); - if (this.StringValue == itemValue) - { - // Add the Selected Attribute - writer.AddAttribute(HtmlTextWriterAttribute.Selected, "selected"); - } - - // Render Option Tag - writer.RenderBeginTag(HtmlTextWriterTag.Option); - switch (this.TextField) - { - case ListBoundField.Id: - writer.Write(item.EntryID.ToString()); - break; - case ListBoundField.Text: - writer.Write(item.Text); - break; - case ListBoundField.Value: - writer.Write(item.Value.Trim()); - break; - } - - writer.RenderEndTag(); - } - - // Close Select Tag - writer.RenderEndTag(); - } - - private PropertyEditorEventArgs GetEventArgs() - { - var args = new PropertyEditorEventArgs(this.Name); - if (this.ValueField == ListBoundField.Id) - { - // This is an Integer Value - args.Value = this.IntegerValue; - args.OldValue = this.OldIntegerValue; - } - else - { - // This is a String Value - args.Value = this.StringValue; - args.OldValue = this.OldStringValue; - } - - args.StringValue = this.StringValue; - return args; - } - } -} + /// RenderViewMode renders the View (readonly) mode of the control. + /// A HtmlTextWriter. + protected override void RenderViewMode(HtmlTextWriter writer) + { + var objListController = new ListController(); + ListEntryInfo entry = null; + string entryText = Null.NullString; + switch (this.ValueField) + { + case ListBoundField.Id: + entry = objListController.GetListEntryInfo(this.ListName, Convert.ToInt32(this.Value)); + break; + case ListBoundField.Text: + entryText = this.StringValue; + break; + case ListBoundField.Value: + entry = objListController.GetListEntryInfo(this.ListName, this.StringValue); + break; + } + + this.ControlStyle.AddAttributesToRender(writer); + writer.RenderBeginTag(HtmlTextWriterTag.Span); + if (entry != null) + { + switch (this.TextField) + { + case ListBoundField.Id: + writer.Write(entry.EntryID.ToString()); + break; + case ListBoundField.Text: + writer.Write(entry.Text); + break; + case ListBoundField.Value: + writer.Write(entry.Value); + break; + } + } + else + { + writer.Write(entryText); + } + + // Close Select Tag + writer.RenderEndTag(); + } + + /// RenderEditMode renders the Edit mode of the control. + /// A HtmlTextWriter. + protected override void RenderEditMode(HtmlTextWriter writer) + { + // Render the Select Tag + this.ControlStyle.AddAttributesToRender(writer); + writer.AddAttribute(HtmlTextWriterAttribute.Name, this.UniqueID); + writer.AddAttribute(HtmlTextWriterAttribute.Id, this.ClientID); + writer.AddAttribute("data-name", this.Name); + writer.AddAttribute("data-list", this.ListName); + writer.AddAttribute("data-category", this.Category); + writer.AddAttribute("data-editor", "DNNListEditControl"); + if (this.AutoPostBack) + { + writer.AddAttribute(HtmlTextWriterAttribute.Onchange, this.Page.ClientScript.GetPostBackEventReference(this, this.ID)); + } + + writer.RenderBeginTag(HtmlTextWriterTag.Select); + + // Add the Not Specified Option + if (this.ValueField == ListBoundField.Text) + { + writer.AddAttribute(HtmlTextWriterAttribute.Value, Null.NullString); + } + else + { + writer.AddAttribute(HtmlTextWriterAttribute.Value, Null.NullString); + } + + if (this.StringValue == Null.NullString) + { + // Add the Selected Attribute + writer.AddAttribute(HtmlTextWriterAttribute.Selected, "selected"); + } + + var defaultText = HttpUtility.HtmlEncode("<" + Localization.GetString("Not_Specified", Localization.SharedResourceFile) + ">"); + writer.RenderBeginTag(HtmlTextWriterTag.Option); + writer.Write(defaultText); + writer.RenderEndTag(); + + foreach (ListEntryInfo item in this.ListEntries) + { + string itemValue = Null.NullString; + + // Add the Value Attribute + switch (this.ValueField) + { + case ListBoundField.Id: + itemValue = item.EntryID.ToString(); + break; + case ListBoundField.Text: + itemValue = item.Text; + break; + case ListBoundField.Value: + itemValue = item.Value; + break; + } + + writer.AddAttribute(HtmlTextWriterAttribute.Value, itemValue); + if (this.StringValue == itemValue) + { + // Add the Selected Attribute + writer.AddAttribute(HtmlTextWriterAttribute.Selected, "selected"); + } + + // Render Option Tag + writer.RenderBeginTag(HtmlTextWriterTag.Option); + switch (this.TextField) + { + case ListBoundField.Id: + writer.Write(item.EntryID.ToString()); + break; + case ListBoundField.Text: + writer.Write(item.Text); + break; + case ListBoundField.Value: + writer.Write(item.Value.Trim()); + break; + } + + writer.RenderEndTag(); + } + + // Close Select Tag + writer.RenderEndTag(); + } + + private PropertyEditorEventArgs GetEventArgs() + { + var args = new PropertyEditorEventArgs(this.Name); + if (this.ValueField == ListBoundField.Id) + { + // This is an Integer Value + args.Value = this.IntegerValue; + args.OldValue = this.OldIntegerValue; + } + else + { + // This is a String Value + args.Value = this.StringValue; + args.OldValue = this.OldStringValue; + } + + args.StringValue = this.StringValue; + return args; + } + } +} diff --git a/DNN Platform/Library/WebControls/WebControlBase.cs b/DNN Platform/Library/WebControls/WebControlBase.cs index 30096c8130b..4e529563b43 100644 --- a/DNN Platform/Library/WebControls/WebControlBase.cs +++ b/DNN Platform/Library/WebControls/WebControlBase.cs @@ -39,7 +39,7 @@ public bool IsHostMenu /// Gets the portal settings for the portal where the WebControl is displayed. [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Obsolete("Deprecated in 9.8, use PortalController.Instance.GetCurrentSettings() instead, if you need access to the ActiveTab, use TabController.CurrentPage. Scheduled removal in v11.0.0.")] + [Obsolete("Deprecated in DotNetNuke 9.8.0. Use PortalController.Instance.GetCurrentSettings() instead, if you need access to the ActiveTab, use TabController.CurrentPage. Scheduled for removal in v11.0.0.")] public PortalSettings PortalSettings { get @@ -54,7 +54,7 @@ public PortalSettings PortalSettings public abstract string HtmlOutput { get; } /// Gets a value indicating whether this WebControl is currently displayed in the admin menu. - [Obsolete("There is no longer the concept of an Admin Page. All pages are controlled by Permissions. Scheduled removal in v11.0.0.", true)] + [Obsolete("Deprecated in DotNetNuke 7.0.0. There is no longer the concept of an Admin Page. All pages are controlled by Permissions. Scheduled for removal in v11.0.0.", true)] public bool IsAdminMenu { get diff --git a/DNN Platform/Library/packages.config b/DNN Platform/Library/packages.config index 430f4aeb128..2627ac895b5 100644 --- a/DNN Platform/Library/packages.config +++ b/DNN Platform/Library/packages.config @@ -14,7 +14,7 @@ - + diff --git a/DNN Platform/Modules/CoreMessaging/DotNetNuke.Modules.CoreMessaging.csproj b/DNN Platform/Modules/CoreMessaging/DotNetNuke.Modules.CoreMessaging.csproj index 49e3a1757db..6c87f78f25e 100644 --- a/DNN Platform/Modules/CoreMessaging/DotNetNuke.Modules.CoreMessaging.csproj +++ b/DNN Platform/Modules/CoreMessaging/DotNetNuke.Modules.CoreMessaging.csproj @@ -42,7 +42,7 @@ bin\DotNetNuke.Modules.CoreMessaging.XML - 7 + latest true @@ -55,7 +55,7 @@ bin\DotNetNuke.Modules.CoreMessaging.XML - 7 + latest true @@ -69,8 +69,7 @@ - ..\..\..\packages\Newtonsoft.Json.13.0.2\lib\net45\Newtonsoft.Json.dll - True + ..\..\..\packages\Newtonsoft.Json.13.0.3\lib\net45\Newtonsoft.Json.dll diff --git a/DNN Platform/Modules/CoreMessaging/View.ascx.cs b/DNN Platform/Modules/CoreMessaging/View.ascx.cs index 5a6589eface..59e0b713252 100644 --- a/DNN Platform/Modules/CoreMessaging/View.ascx.cs +++ b/DNN Platform/Modules/CoreMessaging/View.ascx.cs @@ -95,7 +95,7 @@ protected override void OnInit(EventArgs e) JavaScript.RequestRegistration(CommonJs.DnnPlugins); JavaScript.RequestRegistration(CommonJs.Knockout); ClientResourceManager.RegisterScript(this.Page, "~/DesktopModules/CoreMessaging/Scripts/CoreMessaging.js"); - jQuery.RegisterFileUpload(this.Page); + JavaScript.RequestRegistration(CommonJs.jQueryFileUpload); this.AddIe7StyleSheet(); base.OnInit(e); diff --git a/DNN Platform/Modules/CoreMessaging/packages.config b/DNN Platform/Modules/CoreMessaging/packages.config index 70edc1fe6ea..35a1f217f49 100644 --- a/DNN Platform/Modules/CoreMessaging/packages.config +++ b/DNN Platform/Modules/CoreMessaging/packages.config @@ -4,6 +4,6 @@ - + \ No newline at end of file diff --git a/DNN Platform/Modules/DDRMenu/Controller.cs b/DNN Platform/Modules/DDRMenu/Controller.cs index 60ca2781bbc..4ce483aed1c 100644 --- a/DNN Platform/Modules/DDRMenu/Controller.cs +++ b/DNN Platform/Modules/DDRMenu/Controller.cs @@ -19,19 +19,19 @@ namespace DotNetNuke.Web.DDRMenu public class Controller : IUpgradeable, IPortable { /// Regex for replacement of DNNDoneRight.DDRMenu. - [Obsolete("Deprecated in v9.8.1, this should have not be public, scheduled removal in v10.")] + [Obsolete("Deprecated in DotNetNuke 9.8.1. This should not have been public. Scheduled removal in v10.0.0.")] public static readonly Regex AscxText1Regex = new Regex(Regex.Escape(@"Namespace=""DNNDoneRight.DDRMenu"""), RegexOptions.IgnoreCase | RegexOptions.Compiled); /// Regex for replacement of DNNGarden.TemplateEngine. - [Obsolete("Deprecated in v9.8.1, this should have not be public, scheduled removal in v10.")] + [Obsolete("Deprecated in DotNetNuke 9.8.1. This should not have been public. Scheduled removal in v10.0.0.")] public static readonly Regex AscxText2Regex = new Regex(Regex.Escape(@"Namespace=""DNNGarden.TemplateEngine"""), RegexOptions.IgnoreCase | RegexOptions.Compiled); /// Regex for replacement of DNNDoneRight.DDRMenu. - [Obsolete("Deprecated in v9.8.1, this should have not be public, scheduled removal in v10.")] + [Obsolete("Deprecated in DotNetNuke 9.8.1. This should not have been public. Scheduled removal in v10.0.0.")] public static readonly Regex AscxText3Regex = new Regex(Regex.Escape(@"Assembly=""DNNDoneRight.DDRMenu"""), RegexOptions.IgnoreCase | RegexOptions.Compiled); /// Regex for replacement of DNNGarden.DDRMenu. - [Obsolete("Deprecated in v9.8.1, this should have not be public, scheduled removal in v10.")] + [Obsolete("Deprecated in DotNetNuke 9.8.1. This should not have been public. Scheduled removal in v10.0.0.")] public static readonly Regex AscxText4Regex = new Regex(Regex.Escape(@"Assembly=""DNNGarden.DDRMenu"""), RegexOptions.IgnoreCase | RegexOptions.Compiled); private const string DdrMenuModuleName = "DDRMenu"; diff --git a/DNN Platform/Modules/DDRMenu/DotNetNuke.Modules.DDRMenu.csproj b/DNN Platform/Modules/DDRMenu/DotNetNuke.Modules.DDRMenu.csproj index 2ceff5cada6..4caab8add31 100644 --- a/DNN Platform/Modules/DDRMenu/DotNetNuke.Modules.DDRMenu.csproj +++ b/DNN Platform/Modules/DDRMenu/DotNetNuke.Modules.DDRMenu.csproj @@ -60,7 +60,9 @@ false bin\DotNetNuke.Web.DDRMenu.XML 1591 - 7 + latest + true + CS0618,SA1600,SA1601,SA1614 pdbonly @@ -71,7 +73,9 @@ 4 bin\DotNetNuke.Web.DDRMenu.XML 1591 - 7 + latest + true + CS0618,SA1600,SA1601,SA1614 @@ -223,6 +227,10 @@ + + {5FE5D021-9C8D-47A6-BD34-F328BA3E709C} + DotNetNuke.Internal.SourceGenerators + {6928A9B1-F88A-4581-A132-D3EB38669BB0} DotNetNuke.Abstractions diff --git a/DNN Platform/Modules/DDRMenu/Localisation/Apollo.cs b/DNN Platform/Modules/DDRMenu/Localisation/Apollo.cs index fbaf4ded1cf..fa0ebb1e470 100644 --- a/DNN Platform/Modules/DDRMenu/Localisation/Apollo.cs +++ b/DNN Platform/Modules/DDRMenu/Localisation/Apollo.cs @@ -10,18 +10,19 @@ namespace DotNetNuke.Web.DDRMenu.Localisation using DotNetNuke.Entities.Modules; using DotNetNuke.Entities.Portals; using DotNetNuke.Entities.Tabs; + using DotNetNuke.Internal.SourceGenerators; using DotNetNuke.UI.WebControls; /// Deprecated Apollo localization. - [Obsolete("Deprecated in 9.4.0, due to limited developer support. Scheduled removal in v11.0.0.")] - public class Apollo : ILocalisation + [DnnDeprecated(9, 4, 0, "No replacement", RemovalVersion = 10)] + public partial class Apollo : ILocalisation { private bool haveChecked; private MethodInfo apiMember; - /// - [Obsolete("Deprecated in 9.4.0, due to limited developer support. Scheduled removal in v11.0.0.")] - public bool HaveApi() + /// + [DnnDeprecated(9, 4, 0, "No replacement", RemovalVersion = 10)] + public partial bool HaveApi() { if (!this.haveChecked) { @@ -44,16 +45,16 @@ public bool HaveApi() return this.apiMember != null; } - /// - [Obsolete("Deprecated in 9.4.0, due to limited developer support. Scheduled removal in v11.0.0.")] - public TabInfo LocaliseTab(TabInfo tab, int portalId) + /// + [DnnDeprecated(9, 4, 0, "No replacement", RemovalVersion = 10)] + public partial TabInfo LocaliseTab(TabInfo tab, int portalId) { return this.apiMember.Invoke(null, new object[] { tab }) as TabInfo ?? tab; } - /// - [Obsolete("Deprecated in 9.4.0, due to limited developer support. Scheduled removal in v11.0.0.")] - public DNNNodeCollection LocaliseNodes(DNNNodeCollection nodes) + /// + [DnnDeprecated(9, 4, 0, "No replacement", RemovalVersion = 10)] + public partial DNNNodeCollection LocaliseNodes(DNNNodeCollection nodes) { return null; } diff --git a/DNN Platform/Modules/DDRMenu/Localisation/Ealo.cs b/DNN Platform/Modules/DDRMenu/Localisation/Ealo.cs index 0c1b3cce81e..2d0597a40cb 100644 --- a/DNN Platform/Modules/DDRMenu/Localisation/Ealo.cs +++ b/DNN Platform/Modules/DDRMenu/Localisation/Ealo.cs @@ -4,11 +4,11 @@ namespace DotNetNuke.Web.DDRMenu.Localisation { - using System; using System.Collections.Generic; using DotNetNuke.Entities.Modules; using DotNetNuke.Entities.Portals; + using DotNetNuke.Internal.SourceGenerators; using DotNetNuke.UI.WebControls; using effority.Ealo.Specialized; @@ -16,15 +16,15 @@ namespace DotNetNuke.Web.DDRMenu.Localisation using TabInfo = DotNetNuke.Entities.Tabs.TabInfo; /// Deprecated Ealo localization support. - [Obsolete("Deprecated in 9.4.0, due to limited developer support. Scheduled removal in v11.0.0.")] - public class Ealo : ILocalisation + [DnnDeprecated(9, 4, 0, "No replacement", RemovalVersion = 10)] + public partial class Ealo : ILocalisation { private bool haveChecked; private bool found; - /// - [Obsolete("Deprecated in 9.4.0, due to limited developer support. Scheduled removal in v11.0.0.")] - public bool HaveApi() + /// + [DnnDeprecated(9, 4, 0, "No replacement", RemovalVersion = 10)] + public partial bool HaveApi() { if (!this.haveChecked) { @@ -35,16 +35,16 @@ public bool HaveApi() return this.found; } - /// - [Obsolete("Deprecated in 9.4.0, due to limited developer support. Scheduled removal in v11.0.0.")] - public TabInfo LocaliseTab(TabInfo tab, int portalId) + /// + [DnnDeprecated(9, 4, 0, "No replacement", RemovalVersion = 10)] + public partial TabInfo LocaliseTab(TabInfo tab, int portalId) { return EaloWorker.LocaliseTab(tab, portalId); } - /// - [Obsolete("Deprecated in 9.4.0, due to limited developer support. Scheduled removal in v11.0.0.")] - public DNNNodeCollection LocaliseNodes(DNNNodeCollection nodes) + /// + [DnnDeprecated(9, 4, 0, "No replacement", RemovalVersion = 10)] + public partial DNNNodeCollection LocaliseNodes(DNNNodeCollection nodes) { return null; } diff --git a/DNN Platform/Modules/DDRMenu/MenuBase.cs b/DNN Platform/Modules/DDRMenu/MenuBase.cs index 0e7a153ed1a..f101f72d890 100644 --- a/DNN Platform/Modules/DDRMenu/MenuBase.cs +++ b/DNN Platform/Modules/DDRMenu/MenuBase.cs @@ -46,7 +46,7 @@ public class MenuBase /// Gets the portal settings for the current portal. // TODO: In v11 we should replace this by IPortalSettings and make it private or instantiate PortalSettings in the constructor. - [Obsolete("Deprecated in Dnn 9.8.1, scheduled removal in v11.")] + [Obsolete("Deprecated in DotNetNuke 9.8.1. This should not have been public. Scheduled removal in v11.0.0.")] internal PortalSettings HostPortalSettings { get { return this.hostPortalSettings ?? (this.hostPortalSettings = PortalController.Instance.GetCurrentPortalSettings()); } diff --git a/DNN Platform/Modules/DnnExportImport/Components/Common/Util.cs b/DNN Platform/Modules/DnnExportImport/Components/Common/Util.cs index ca0c5ff748f..3797e1fd66a 100644 --- a/DNN Platform/Modules/DnnExportImport/Components/Common/Util.cs +++ b/DNN Platform/Modules/DnnExportImport/Components/Common/Util.cs @@ -22,10 +22,11 @@ namespace Dnn.ExportImport.Components.Common using DotNetNuke.Entities.Users; using DotNetNuke.Framework.Reflections; using DotNetNuke.Instrumentation; + using DotNetNuke.Internal.SourceGenerators; using Newtonsoft.Json; /// A collection of utilities for import/export. - public static class Util + public static partial class Util { private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(Util)); private static int noRole = Convert.ToInt32(Globals.glbRoleNothing); @@ -33,20 +34,20 @@ public static class Util /// Checks if a string is either null or empty (""). /// The string to check. /// A value indicating whether the string is null or empty. - [Obsolete("Depreacted in v9.8.0, use string.IsNullOrEmpty from System.String instead, scheduled removal in v11.")] - public static bool IsNullOrEmpty(this string s) => string.IsNullOrEmpty(s); + [DnnDeprecated(9, 8, 0, "Use string.IsNullOrEmpty from System.String instead")] + public static partial bool IsNullOrEmpty(this string s) => string.IsNullOrEmpty(s); /// Checks if a string is either null or contains only whitespace (" "). /// The string to check. /// A value indicating whether the string is null or contains only whtespace. - [Obsolete("Depreacted in v9.8.0, use string.IsNullOrWhiteSpace from System.String instead, scheduled removal in v11.")] - public static bool IsNullOrWhiteSpace(this string s) => string.IsNullOrWhiteSpace(s); + [DnnDeprecated(9, 8, 0, "Use string.IsNullOrWhiteSpace from System.String instead")] + public static partial bool IsNullOrWhiteSpace(this string s) => string.IsNullOrWhiteSpace(s); /// Check if a given string is not null or empty (contains any value). /// The string to check. /// A value indicating whether the string contains any value. - [Obsolete("Depracated in v9.8.0 use !string.IsNullOrEmpty from System.String instead, cheduled removal in v11.")] - public static bool HasValue(this string s) => !string.IsNullOrEmpty(s); + [DnnDeprecated(9, 8, 0, "Use !string.IsNullOrEmpty from System.String instead")] + public static partial bool HasValue(this string s) => !string.IsNullOrEmpty(s); /// Gets the types that implement BasePortableService. /// An enumeration of the types that implement BasePortableService. diff --git a/DNN Platform/Modules/DnnExportImport/DnnExportImport.csproj b/DNN Platform/Modules/DnnExportImport/DnnExportImport.csproj index d5654ac32fd..3a6541880e1 100644 --- a/DNN Platform/Modules/DnnExportImport/DnnExportImport.csproj +++ b/DNN Platform/Modules/DnnExportImport/DnnExportImport.csproj @@ -30,7 +30,9 @@ 4 bin\DotNetNuke.SiteExportImport.xml 1591 - 7 + latest + true + CS0618,SA1600,SA1614 pdbonly @@ -41,7 +43,9 @@ 4 bin\DotNetNuke.SiteExportImport.xml 1591 - 7 + latest + true + CS0618,SA1600,SA1614 @@ -49,8 +53,7 @@ - ..\..\..\packages\Newtonsoft.Json.13.0.2\lib\net45\Newtonsoft.Json.dll - True + ..\..\..\packages\Newtonsoft.Json.13.0.3\lib\net45\Newtonsoft.Json.dll @@ -142,6 +145,14 @@ + + {5FE5D021-9C8D-47A6-BD34-F328BA3E709C} + DotNetNuke.Internal.SourceGenerators + + + {6928a9b1-f88a-4581-a132-d3eb38669bb0} + DotNetNuke.Abstractions + {3cd5f6b8-8360-4862-80b6-f402892db7dd} DotNetNuke.Instrumentation @@ -168,6 +179,7 @@ + diff --git a/DNN Platform/Modules/DnnExportImport/Providers/DataProviders/SqlDataProvider/09.12.01.SqlDataProvider b/DNN Platform/Modules/DnnExportImport/Providers/DataProviders/SqlDataProvider/09.12.01.SqlDataProvider new file mode 100644 index 00000000000..f27f22417ea --- /dev/null +++ b/DNN Platform/Modules/DnnExportImport/Providers/DataProviders/SqlDataProvider/09.12.01.SqlDataProvider @@ -0,0 +1,422 @@ +/************************************************************/ +/***** SqlDataProvider *****/ +/***** *****/ +/***** *****/ +/***** Note: To manually execute this script you must *****/ +/***** perform a search and replace operation *****/ +/***** for {databaseOwner} and {objectQualifier} *****/ +/***** *****/ +/************************************************************/ + +/* Fix Improper Table Reference #5552 */ +IF object_id(N'{databaseOwner}[{objectQualifier}ExportImport_AddUpdateUsersBulk]', 'P') IS NOT NULL + DROP PROCEDURE {databaseOwner}[{objectQualifier}ExportImport_AddUpdateUsersBulk] +GO + +CREATE PROCEDURE {databaseOwner}[{objectQualifier}ExportImport_AddUpdateUsersBulk] + @DataTable {databaseOwner}[{objectQualifier}ExportImportUserType] READONLY, + @Overwrite bit = 1 +AS +BEGIN + + DECLARE @MinDate Datetime = cast('1753-1-1' as datetime); + DECLARE @EmptyGuid UNIQUEIDENTIFIER = CAST(CAST(0 AS BINARY) AS UNIQUEIDENTIFIER); + BEGIN TRANSACTION [UsersInsert] + --Update/Insert Users + IF @Overwrite = 1 + BEGIN + --Update Users + SELECT + Users.UserID + ,dt.IsDeleted + ,dt.PortalId + ,dt.FirstName + ,dt.LastName + ,dt.IsSuperUser + ,dt.Email + ,dt.DisplayName + ,dt.UpdatePassword + ,dt.PasswordResetToken + ,dt.PasswordResetExpiration + ,dt.LastIPAddress + ,dt.LastModifiedByUserId + INTO #UserUpdatesDataTable + FROM @DataTable dt + INNER JOIN {databaseOwner}{objectQualifier}Users Users + ON Users.Username= dt.Username + WHERE Users.UserID IS NOT NULL AND dt.IsSuperUser=0 AND Users.IsSuperUser=0 + + UPDATE Users + SET + Users.FirstName = dt.FirstName, + Users.LastName = dt.LastName, + Users.IsSuperUser = dt.IsSuperUser, + Users.Email = dt.Email, + Users.DisplayName = dt.DisplayName, + Users.UpdatePassword = dt.UpdatePassword, + Users.PasswordResetToken = dt.PasswordResetToken, + Users.PasswordResetExpiration = dt.PasswordResetExpiration, + Users.LastIPAddress = dt.LastIPAddress, + Users.LastModifiedByUserID = dt.LastModifiedByUserId, + Users.LastModifiedOnDate = getdate(), + Users.IsDeleted = CASE WHEN dt.PortalId IS NULL THEN dt.IsDeleted ELSE Users.IsDeleted END + FROM {databaseOwner}{objectQualifier}Users AS Users + INNER JOIN #UserUpdatesDataTable AS dt ON Users.UserID=dt.UserID + + DROP TABLE #UserUpdatesDataTable; + END + --Insert new Users + SELECT Users.UserID, + dt.Username, + dt.FirstName, + dt.LastName, + dt.AffiliateId, + dt.IsSuperUser, + dt.Email, + dt.DisplayName, + dt.UpdatePassword, + dt.CreatedByUserId, + dt.LastModifiedByUserId + INTO #UserInsertsDataTable + FROM @DataTable dt + LEFT JOIN {databaseOwner}{objectQualifier}Users Users ON Users.Username = dt.Username + WHERE Users.UserID IS NULL AND dt.IsSuperUser=0 AND ISNULL(Users.IsSuperUser, 0)=0 + + INSERT INTO {databaseOwner}{objectQualifier}Users ( + Username, + FirstName, + LastName, + AffiliateId, + IsSuperUser, + Email, + DisplayName, + UpdatePassword, + CreatedByUserID, + CreatedOnDate, + LastModifiedByUserID, + LastModifiedOnDate + ) + SELECT + dt.Username, + dt.FirstName, + dt.LastName, + dt.AffiliateId, + dt.IsSuperUser, + dt.Email, + dt.DisplayName, + dt.UpdatePassword, + dt.CreatedByUserId, + getdate(), + dt.LastModifiedByUserId, + getdate() + FROM + #UserInsertsDataTable dt + + DROP TABLE #UserInsertsDataTable; + + --Update/Insert User Portals + IF @Overwrite = 1 + BEGIN + --Update User Portals + SELECT + UP.UserPortalId + ,dt.IsDeleted + ,dt.Authorised + ,dt.RefreshRoles + ,dt.VanityUrl + ,dt.PortalId + INTO #UP_UpdatesDataTable + FROM @DataTable dt + INNER JOIN {databaseOwner}{objectQualifier}Users Users ON Users.Username= dt.Username + INNER JOIN {databaseOwner}{objectQualifier}UserPortals UP ON UP.UserId= Users.UserID + WHERE Users.UserID IS NOT NULL AND UP.UserPortalId IS NOT NULL AND UP.PortalId=dt.PortalId + AND dt.IsDeleted IS NOT NULL AND dt.Authorised IS NOT NULL AND dt.RefreshRoles IS NOT NULL AND dt.IsSuperUser=0 AND Users.IsSuperUser=0 + + UPDATE UserPortals + SET + Authorised = dt.Authorised, + RefreshRoles = dt.RefreshRoles, + VanityUrl = dt.VanityUrl, + IsDeleted = dt.IsDeleted + FROM {databaseOwner}{objectQualifier}UserPortals AS UserPortals + INNER JOIN #UP_UpdatesDataTable AS dt ON UserPortals.UserPortalId=dt.UserPortalId + + DROP TABLE #UP_UpdatesDataTable; + END + --Inser User Portals + SELECT + Users.UserId, + UP.UserPortalId + ,dt.IsDeleted + ,dt.Authorised + ,dt.RefreshRoles + ,dt.VanityUrl + ,dt.PortalId + INTO #UP_InsertsDataTable + FROM @DataTable dt + INNER JOIN {databaseOwner}{objectQualifier}Users Users ON Users.Username= dt.Username + LEFT JOIN {databaseOwner}{objectQualifier}UserPortals UP ON UP.UserId= Users.UserID AND UP.PortalId=dt.PortalId + WHERE Users.UserID IS NOT NULL AND UP.UserPortalId IS NULL + AND dt.IsDeleted IS NOT NULL AND dt.Authorised IS NOT NULL AND dt.RefreshRoles IS NOT NULL AND dt.IsSuperUser=0 AND ISNULL(Users.IsSuperUser, 0)=0 + + INSERT INTO {databaseOwner}{objectQualifier}UserPortals ( + [UserId] + ,[PortalId] + ,[CreatedDate] + ,[Authorised] + ,[IsDeleted] + ,[RefreshRoles] + ,[VanityUrl]) + SELECT + dt.[UserId] + ,dt.[PortalId] + ,getdate() + ,dt.[Authorised] + ,dt.[IsDeleted] + ,dt.[RefreshRoles] + ,dt.[VanityUrl] + FROM #UP_InsertsDataTable dt + DROP TABLE #UP_InsertsDataTable; + + ----Update/Insert User Authentication + IF @Overwrite = 1 + BEGIN + SELECT + UserAuthentication.UserAuthenticationID + ,dt.AuthenticationType + ,dt.AuthenticationToken + ,dt.LastModifiedByUserId + INTO #UserAuthenticationUpdatesDataTable + FROM @DataTable dt INNER JOIN {databaseOwner}{objectQualifier}Users Users ON Users.Username=dt.Username + INNER JOIN {databaseOwner}{objectQualifier}UserPortals UP ON UP.UserId=Users.UserID AND UP.PortalId=dt.PortalId + INNER JOIN {databaseOwner}{objectQualifier}UserAuthentication UserAuthentication ON UserAuthentication.UserID=Users.UserID AND LTRIM(RTRIM(UserAuthentication.AuthenticationType)) = LTRIM(RTRIM(dt.AuthenticationType)) + WHERE Users.UserID IS NOT NULL AND UP.UserPortalId IS NOT NULL AND UP.PortalId=dt.PortalId AND UserAuthentication.UserAuthenticationID IS NOT NULL AND dt.AuthenticationToken IS NOT NULL AND dt.AuthenticationType IS NOT NULL AND dt.IsSuperUser=0 AND Users.IsSuperUser=0 + + UPDATE UserAuthentication + SET + UserAuthentication.AuthenticationToken = dt.AuthenticationToken, + UserAuthentication.LastModifiedByUserID = dt.LastModifiedByUserId, + UserAuthentication.LastModifiedOnDate = GETDATE() + FROM {databaseOwner}{objectQualifier}UserAuthentication AS UserAuthentication + INNER JOIN #UserAuthenticationUpdatesDataTable AS dt ON UserAuthentication.UserAuthenticationID=dt.UserAuthenticationID + + DROP TABLE #UserAuthenticationUpdatesDataTable; + END + + --Insert new UserAuthentication + SELECT + Users.UserID + ,dt.AuthenticationType + ,dt.AuthenticationToken + ,dt.CreatedByUserId + ,dt.LastModifiedByUserId + INTO #UserAuthenticationInsertsDataTable + FROM @DataTable dt INNER JOIN {databaseOwner}{objectQualifier}Users Users ON Users.Username=dt.Username + INNER JOIN {databaseOwner}{objectQualifier}UserPortals UP ON UP.UserId=Users.UserID AND UP.PortalId=dt.PortalId + LEFT JOIN {databaseOwner}{objectQualifier}UserAuthentication UserAuthentication ON UserAuthentication.UserID=Users.UserID AND LTRIM(RTRIM(UserAuthentication.AuthenticationType)) = LTRIM(RTRIM(dt.AuthenticationType)) + WHERE Users.UserID IS NOT NULL AND UP.UserPortalId IS NOT NULL AND UP.PortalId=dt.PortalId AND UserAuthentication.UserAuthenticationID IS NULL AND dt.IsSuperUser=0 AND ISNULL(Users.IsSuperUser, 0)=0 + AND dt.AuthenticationToken IS NOT NULL AND dt.AuthenticationType IS NOT NULL + + INSERT INTO {databaseOwner}[{objectQualifier}UserAuthentication]( + UserID + ,AuthenticationType + ,AuthenticationToken + ,CreatedByUserID + ,CreatedOnDate + ,LastModifiedByUserID + ,LastModifiedOnDate + ) + SELECT + dt.UserID, + dt.AuthenticationType, + dt.AuthenticationToken, + dt.CreatedByUserId, + GETDATE(), + dt.LastModifiedByUserId, + GETDATE() + FROM + #UserAuthenticationInsertsDataTable dt + + DROP TABLE #UserAuthenticationInsertsDataTable; + + --Update/Insert aspnet_Users + IF @Overwrite = 1 + BEGIN + --Update aspnet_Users + SELECT + AspUsers.UserId + ,dt.Username + ,dt.[ApplicationId] + ,dt.[MobileAlias] + ,dt.[IsAnonymous] + INTO #AspNetUserUpdatesDataTable + FROM @DataTable dt INNER JOIN {databaseOwner}aspnet_Users AspUsers ON AspUsers.Username= dt.Username + INNER JOIN {databaseOwner}{objectQualifier}Users Users ON Users.Username=dt.Username + WHERE AspUsers.UserId IS NOT NULL AND dt.AspUserId <> @EmptyGuid AND dt.[IsAnonymous] IS NOT NULL AND dt.[ApplicationId] IS NOT NULL AND dt.IsSuperUser=0 AND Users.IsSuperUser=0 + + UPDATE Users + SET + Users.UserName = dt.Username, + Users.[LoweredUserName] = LOWER(dt.Username), + Users.[MobileAlias] = dt.[MobileAlias], + Users.[IsAnonymous] = dt.[IsAnonymous], + Users.[LastActivityDate] = GETUTCDATE() + FROM {databaseOwner}aspnet_Users AS Users + INNER JOIN #AspNetUserUpdatesDataTable AS dt + ON Users.UserID=dt.UserID AND Users.ApplicationId=dt.[ApplicationId] + + DROP TABLE #AspNetUserUpdatesDataTable + END + --Insert aspnet_Users + SELECT + dt.Username + ,dt.[ApplicationId] + ,dt.[MobileAlias] + ,dt.[IsAnonymous] + + INTO #AspNetUserInsertsDataTable + FROM @DataTable dt + LEFT JOIN {databaseOwner}aspnet_Users AspUsers ON AspUsers.Username= dt.Username + INNER JOIN {databaseOwner}{objectQualifier}Users Users ON Users.Username=dt.Username + WHERE AspUsers.UserId IS NULL AND dt.AspUserId <> @EmptyGuid AND dt.[IsAnonymous] IS NOT NULL AND dt.[ApplicationId] IS NOT NULL AND dt.IsSuperUser=0 AND ISNULL(Users.IsSuperUser, 0)=0 + + INSERT INTO {databaseOwner}[aspnet_Users] + ([ApplicationId] + ,[UserName] + ,[LoweredUserName] + ,[MobileAlias] + ,[IsAnonymous] + ,[LastActivityDate]) + SELECT + dt.[ApplicationId] + ,dt.[Username] + ,LOWER(dt.[Username]) + ,dt.[MobileAlias] + ,dt.[IsAnonymous] + ,GETUTCDATE() + FROM #AspNetUserInsertsDataTable dt + + DROP TABLE #AspNetUserInsertsDataTable + + --Update/Insert aspnet_Membership + IF @Overwrite = 1 + BEGIN + --Update aspnet_Membership + SELECT + dt.[ApplicationId] + ,AspUsers.UserId + ,dt.[Password] + ,dt.[PasswordFormat] + ,dt.[PasswordSalt] + ,dt.[MobilePIN] + ,dt.[Email] + ,dt.[PasswordQuestion] + ,dt.[PasswordAnswer] + ,dt.[IsApproved] + ,dt.[IsLockedOut] + ,dt.[FailedPasswordAttemptCount] + ,dt.[FailedPasswordAnswerAttemptCount] + ,dt.[Comment] + INTO #AspNetMembershipUpdatesDataTable + FROM @DataTable dt INNER JOIN {databaseOwner}aspnet_Users AspUsers ON AspUsers.Username= dt.Username + INNER JOIN {databaseOwner}{objectQualifier}Users Users ON Users.Username=dt.Username + INNER JOIN {databaseOwner}aspnet_Membership Membership ON Membership.UserId= AspUsers.UserID AND Membership.ApplicationId=AspUsers.ApplicationId + WHERE AspUsers.UserId IS NOT NULL AND Membership.UserId IS NOT NULL AND dt.AspUserId <> @EmptyGuid AND dt.Password IS NOT NULL + AND dt.[PasswordFormat] IS NOT NULL AND dt.[PasswordSalt] IS NOT NULL AND dt.[IsApproved] IS NOT NULL AND dt.[IsLockedOut] IS NOT NULL + AND dt.[FailedPasswordAttemptCount] IS NOT NULL AND dt.[FailedPasswordAnswerAttemptCount] IS NOT NULL AND dt.IsSuperUser=0 AND Users.IsSuperUser=0 + + UPDATE {databaseOwner}aspnet_Membership + SET + [Password] =dt.[Password] + ,[PasswordFormat] =dt.[PasswordFormat] + ,[PasswordSalt] =dt.[PasswordSalt] + ,[MobilePIN] =dt.[MobilePIN] + ,[Email] =dt.[Email] + ,[PasswordQuestion] =dt.[PasswordQuestion] + ,[PasswordAnswer] =dt.[PasswordAnswer] + ,[IsApproved] =dt.[IsApproved] + ,[IsLockedOut] =dt.[IsLockedOut] + ,[FailedPasswordAttemptCount] =dt.[FailedPasswordAttemptCount] + ,[FailedPasswordAnswerAttemptCount] =dt.[FailedPasswordAnswerAttemptCount] + ,[Comment] =dt.[Comment] + FROM {databaseOwner}aspnet_Membership AS Membership + INNER JOIN #AspNetMembershipUpdatesDataTable AS dt ON Membership.UserId=dt.UserId AND Membership.[ApplicationId]=dt.[ApplicationId] + + DROP TABLE #AspNetMembershipUpdatesDataTable + END + --Insert aspnet_Membership + SELECT + dt.[ApplicationId] + ,AspUsers.UserId + ,dt.[Password] + ,dt.[PasswordFormat] + ,dt.[PasswordSalt] + ,dt.[MobilePIN] + ,dt.[Email] + ,dt.[PasswordQuestion] + ,dt.[PasswordAnswer] + ,dt.[IsApproved] + ,dt.[IsLockedOut] + ,dt.[FailedPasswordAttemptCount] + ,dt.[FailedPasswordAnswerAttemptCount] + ,dt.[Comment] + INTO #AspNetMembershipInsertsDataTable + FROM @DataTable dt INNER JOIN {databaseOwner}aspnet_Users AspUsers ON AspUsers.Username= dt.Username + INNER JOIN {databaseOwner}{objectQualifier}Users Users ON Users.Username=dt.Username + LEFT JOIN {databaseOwner}aspnet_Membership Membership ON Membership.UserId= AspUsers.UserID AND Membership.ApplicationId=AspUsers.ApplicationId + WHERE AspUsers.UserId IS NOT NULL AND Membership.UserId IS NULL AND dt.AspUserId <> @EmptyGuid AND dt.Password IS NOT NULL + AND dt.[PasswordFormat] IS NOT NULL AND dt.[PasswordSalt] IS NOT NULL AND dt.[IsApproved] IS NOT NULL AND dt.[IsLockedOut] IS NOT NULL + AND dt.[FailedPasswordAttemptCount] IS NOT NULL AND dt.[FailedPasswordAnswerAttemptCount] IS NOT NULL AND dt.IsSuperUser=0 AND ISNULL(Users.IsSuperUser, 0)=0 + + INSERT INTO {databaseOwner}[aspnet_Membership] + ([ApplicationId] + ,[UserId] + ,[Password] + ,[PasswordFormat] + ,[PasswordSalt] + ,[MobilePIN] + ,[Email] + ,[LoweredEmail] + ,[PasswordQuestion] + ,[PasswordAnswer] + ,[IsApproved] + ,[IsLockedOut] + ,[CreateDate] + ,[LastLoginDate] + ,[LastPasswordChangedDate] + ,[LastLockoutDate] + ,[FailedPasswordAttemptCount] + ,[FailedPasswordAttemptWindowStart] + ,[FailedPasswordAnswerAttemptCount] + ,[FailedPasswordAnswerAttemptWindowStart] + ,[Comment]) + SELECT + dt.[ApplicationId] + ,dt.[UserId] + ,dt.[Password] + ,dt.[PasswordFormat] + ,dt.[PasswordSalt] + ,dt.[MobilePIN] + ,dt.[Email] + ,LOWER(dt.[Email]) + ,dt.[PasswordQuestion] + ,dt.[PasswordAnswer] + ,dt.[IsApproved] + ,dt.[IsLockedOut] + ,GETUTCDATE() + ,@MinDate + ,@MinDate + ,@MinDate + ,dt.[FailedPasswordAttemptCount] + ,@MinDate + ,dt.[FailedPasswordAnswerAttemptCount] + ,@MinDate + ,dt.[Comment] + FROM #AspNetMembershipInsertsDataTable dt + DROP TABLE #AspNetMembershipInsertsDataTable + + COMMIT TRANSACTION [UsersInsert] + +END + +GO \ No newline at end of file diff --git a/DNN Platform/Modules/DnnExportImport/packages.config b/DNN Platform/Modules/DnnExportImport/packages.config index 2751e3796a6..4171ede85c3 100644 --- a/DNN Platform/Modules/DnnExportImport/packages.config +++ b/DNN Platform/Modules/DnnExportImport/packages.config @@ -6,6 +6,6 @@ - + \ No newline at end of file diff --git a/DNN Platform/Modules/DnnExportImportLibrary/DnnExportImportLibrary.csproj b/DNN Platform/Modules/DnnExportImportLibrary/DnnExportImportLibrary.csproj index 9bfc4d9b50c..5b6604ff4a9 100644 --- a/DNN Platform/Modules/DnnExportImportLibrary/DnnExportImportLibrary.csproj +++ b/DNN Platform/Modules/DnnExportImportLibrary/DnnExportImportLibrary.csproj @@ -25,21 +25,27 @@ full false bin\Debug\ + bin\Debug\Dnn.ExportImportLibrary.XML DEBUG;TRACE prompt 4 1591 - 7 + latest + true + CS0618,SA1600 pdbonly true bin\Release\ + bin\Release\Dnn.ExportImportLibrary.XML TRACE prompt 4 1591 - 7 + latest + true + CS0618,SA1600 diff --git a/DNN Platform/Modules/DnnExportImportLibrary/Dto/Pages/ExportTabModule.cs b/DNN Platform/Modules/DnnExportImportLibrary/Dto/Pages/ExportTabModule.cs index 07f284cded9..f457c326916 100644 --- a/DNN Platform/Modules/DnnExportImportLibrary/Dto/Pages/ExportTabModule.cs +++ b/DNN Platform/Modules/DnnExportImportLibrary/Dto/Pages/ExportTabModule.cs @@ -39,16 +39,16 @@ public class ExportTabModule : BasicExportImportDto public bool DisplaySyndicate { get; set; } - [Obsolete("WebSlice functionality is no longer used. Will be removed in v10.0.0")] + [Obsolete("Deprecated in DotNetNuke 9.8.0. WebSlice functionality is no longer used. Scheduled removal in v10.0.0.")] public bool IsWebSlice { get; set; } - [Obsolete("WebSlice functionality is no longer used. Will be removed in v10.0.0")] + [Obsolete("Deprecated in DotNetNuke 9.8.0. WebSlice functionality is no longer used. Scheduled removal in v10.0.0.")] public string WebSliceTitle { get; set; } - [Obsolete("WebSlice functionality is no longer used. Will be removed in v10.0.0")] + [Obsolete("Deprecated in DotNetNuke 9.8.0. WebSlice functionality is no longer used. Scheduled removal in v10.0.0.")] public DateTime? WebSliceExpiryDate { get; set; } - [Obsolete("WebSlice functionality is no longer used. Will be removed in v10.0.0")] + [Obsolete("Deprecated in DotNetNuke 9.8.0. WebSlice functionality is no longer used. Scheduled removal in v10.0.0.")] public int? WebSliceTTL { get; set; } public int? CreatedByUserID { get; set; } diff --git a/DNN Platform/Modules/Groups/DotNetNuke.Modules.Groups.csproj b/DNN Platform/Modules/Groups/DotNetNuke.Modules.Groups.csproj index 29500b8d7a0..ffc4c58406d 100644 --- a/DNN Platform/Modules/Groups/DotNetNuke.Modules.Groups.csproj +++ b/DNN Platform/Modules/Groups/DotNetNuke.Modules.Groups.csproj @@ -33,7 +33,9 @@ 1 AllRules.ruleset 1591 - 7 + latest + true + CS0618,CS3008,SA1600,SA1601,SA1602,SA1611,SA1614 pdbonly @@ -43,7 +45,9 @@ Bin\DotNetNuke.Modules.Groups.XML AllRules.ruleset 1591 - 7 + latest + true + CS0618,CS3008,SA1600,SA1601,SA1602,SA1611,SA1614 @@ -61,8 +65,7 @@ ..\..\..\packages\Microsoft.Extensions.DependencyInjection.Abstractions.2.1.1\lib\netstandard2.0\Microsoft.Extensions.DependencyInjection.Abstractions.dll - ..\..\..\packages\Newtonsoft.Json.13.0.2\lib\net45\Newtonsoft.Json.dll - True + ..\..\..\packages\Newtonsoft.Json.13.0.3\lib\net45\Newtonsoft.Json.dll diff --git a/DNN Platform/Modules/Groups/packages.config b/DNN Platform/Modules/Groups/packages.config index a0229fe8927..8b4ec405821 100644 --- a/DNN Platform/Modules/Groups/packages.config +++ b/DNN Platform/Modules/Groups/packages.config @@ -6,6 +6,6 @@ - + \ No newline at end of file diff --git a/DNN Platform/Modules/HTML/Components/HtmlTextController.cs b/DNN Platform/Modules/HTML/Components/HtmlTextController.cs index bab072f33a5..c6c75ec2b36 100644 --- a/DNN Platform/Modules/HTML/Components/HtmlTextController.cs +++ b/DNN Platform/Modules/HTML/Components/HtmlTextController.cs @@ -21,6 +21,7 @@ namespace DotNetNuke.Modules.Html using DotNetNuke.Entities.Portals; using DotNetNuke.Entities.Tabs; using DotNetNuke.Entities.Users; + using DotNetNuke.Internal.SourceGenerators; using DotNetNuke.Modules.Html.Components; using DotNetNuke.Security; using DotNetNuke.Security.Permissions; @@ -34,7 +35,7 @@ namespace DotNetNuke.Modules.Html using Microsoft.Extensions.DependencyInjection; /// The HtmlTextController is the Controller class for managing HtmlText information the HtmlText module. - public class HtmlTextController : ModuleSearchBase, IPortable, IUpgradeable + public partial class HtmlTextController : ModuleSearchBase, IPortable, IUpgradeable { [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1310:FieldNamesMustNotContainUnderscore", Justification = "Breaking Change")] public const int MAX_DESCRIPTION_LENGTH = 100; @@ -87,8 +88,8 @@ public static string FormatHtmlText(int moduleId, string content, HtmlModuleSett return content; } - [Obsolete("Deprecated in Platform 9.11.0. Use overload without int. Scheduled removal in v11.0.0.")] - public static string ManageRelativePaths(string htmlContent, string strUploadDirectory, string strToken, int intPortalID) + [DnnDeprecated(9, 11, 0, "Use overload without int")] + public static partial string ManageRelativePaths(string htmlContent, string strUploadDirectory, string strToken, int intPortalID) { return ManageRelativePaths(htmlContent, strUploadDirectory, strToken); } diff --git a/DNN Platform/Modules/HTML/DotNetNuke.Modules.Html.csproj b/DNN Platform/Modules/HTML/DotNetNuke.Modules.Html.csproj index 755a3916832..04a58d10c72 100644 --- a/DNN Platform/Modules/HTML/DotNetNuke.Modules.Html.csproj +++ b/DNN Platform/Modules/HTML/DotNetNuke.Modules.Html.csproj @@ -42,7 +42,9 @@ bin\DotNetNuke.Modules.Html.XML 1591 AllRules.ruleset - 7 + latest + true + CS0618,SA1600,SA1601,SA1611,SA1614 pdbonly @@ -53,7 +55,9 @@ bin\DotNetNuke.Modules.Html.XML 1591 AllRules.ruleset - 7 + latest + true + CS0618,SA1600,SA1601,SA1611,SA1614 zip @@ -215,6 +219,10 @@ + + {5FE5D021-9C8D-47A6-BD34-F328BA3E709C} + DotNetNuke.Internal.SourceGenerators + {6928A9B1-F88A-4581-A132-D3EB38669BB0} DotNetNuke.Abstractions diff --git a/DNN Platform/Modules/HtmlEditorManager/DotNetNuke.Modules.HtmlEditorManager.csproj b/DNN Platform/Modules/HtmlEditorManager/DotNetNuke.Modules.HtmlEditorManager.csproj index d4c8e394633..eeaaeddccef 100644 --- a/DNN Platform/Modules/HtmlEditorManager/DotNetNuke.Modules.HtmlEditorManager.csproj +++ b/DNN Platform/Modules/HtmlEditorManager/DotNetNuke.Modules.HtmlEditorManager.csproj @@ -43,7 +43,9 @@ Auto bin\DotNetNuke.Modules.HtmlEditorManager.xml 1591 - 7 + latest + true + CS0618,SA1600 pdbonly @@ -55,7 +57,9 @@ bin\DotNetNuke.Modules.HtmlEditorManager.xml 1591 Auto - 7 + latest + true + CS0618,SA1600 @@ -142,6 +146,10 @@ + + {5FE5D021-9C8D-47A6-BD34-F328BA3E709C} + DotNetNuke.Internal.SourceGenerators + {6928A9B1-F88A-4581-A132-D3EB38669BB0} DotNetNuke.Abstractions diff --git a/DNN Platform/Modules/HtmlEditorManager/Presenters/ProviderConfigurationPresenter.cs b/DNN Platform/Modules/HtmlEditorManager/Presenters/ProviderConfigurationPresenter.cs index 0475ce0aaed..8a8dfcfdce8 100644 --- a/DNN Platform/Modules/HtmlEditorManager/Presenters/ProviderConfigurationPresenter.cs +++ b/DNN Platform/Modules/HtmlEditorManager/Presenters/ProviderConfigurationPresenter.cs @@ -14,6 +14,7 @@ namespace DotNetNuke.Modules.HtmlEditorManager.Presenters using DotNetNuke.Common.Utilities; using DotNetNuke.Entities.Modules; using DotNetNuke.Entities.Users; + using DotNetNuke.Internal.SourceGenerators; using DotNetNuke.Modules.HtmlEditorManager.ViewModels; using DotNetNuke.Modules.HtmlEditorManager.Views; using DotNetNuke.Web.Client.ClientResourceManagement; @@ -22,8 +23,8 @@ namespace DotNetNuke.Modules.HtmlEditorManager.Presenters using DotNetNuke.Web.UI.WebControls; /// Presenter for Provider Configuration. - [Obsolete("Deprecated in DNN 9.2.0. Replace WebFormsMvp and DotNetNuke.Web.Mvp with MVC or SPA patterns instead. Scheduled removal in v11.0.0.")] - public class ProviderConfigurationPresenter : ModulePresenter + [DnnDeprecated(9, 2, 0, "Replace WebFormsMvp and DotNetNuke.Web.Mvp with MVC or SPA patterns instead")] + public partial class ProviderConfigurationPresenter : ModulePresenter { /// The HTML editor node. private const string HtmlEditorNode = "/configuration/dotnetnuke/htmlEditor"; diff --git a/DNN Platform/Modules/HtmlEditorManager/Views/IProviderConfigurationView.cs b/DNN Platform/Modules/HtmlEditorManager/Views/IProviderConfigurationView.cs index 66caa755234..255c3e981c6 100644 --- a/DNN Platform/Modules/HtmlEditorManager/Views/IProviderConfigurationView.cs +++ b/DNN Platform/Modules/HtmlEditorManager/Views/IProviderConfigurationView.cs @@ -6,12 +6,13 @@ namespace DotNetNuke.Modules.HtmlEditorManager.Views using System; using System.Web.UI.WebControls; + using DotNetNuke.Internal.SourceGenerators; using DotNetNuke.Modules.HtmlEditorManager.ViewModels; using DotNetNuke.Web.Mvp; /// Interface for the Provider Configuration View. - [Obsolete("Deprecated in DNN 9.2.0. Replace WebFormsMvp and DotNetNuke.Web.Mvp with MVC or SPA patterns instead. Scheduled removal in v11.0.0.")] - public interface IProviderConfigurationView : IModuleView + [DnnDeprecated(9, 2, 0, "Replace WebFormsMvp and DotNetNuke.Web.Mvp with MVC or SPA patterns instead")] + public partial interface IProviderConfigurationView : IModuleView { /// Occurs when [save editor choice]. event EventHandler SaveEditorChoice; diff --git a/DNN Platform/Modules/HtmlEditorManager/Views/ProviderConfiguration.ascx.cs b/DNN Platform/Modules/HtmlEditorManager/Views/ProviderConfiguration.ascx.cs index eb2669bacfa..ea9e6f1431c 100644 --- a/DNN Platform/Modules/HtmlEditorManager/Views/ProviderConfiguration.ascx.cs +++ b/DNN Platform/Modules/HtmlEditorManager/Views/ProviderConfiguration.ascx.cs @@ -9,11 +9,12 @@ namespace DotNetNuke.Modules.HtmlEditorManager.Views using DotNetNuke.Common; using DotNetNuke.Entities.Users; + using DotNetNuke.Internal.SourceGenerators; using DotNetNuke.Modules.HtmlEditorManager.ViewModels; using DotNetNuke.Web.Mvp; /// View control for selecting an HTML provider. - [Obsolete("Deprecated in DNN 9.2.0. Replace WebFormsMvp and DotNetNuke.Web.Mvp with MVC or SPA patterns instead. Scheduled removal in v11.0.0.")] + [DnnDeprecated(9, 2, 0, "Replace WebFormsMvp and DotNetNuke.Web.Mvp with MVC or SPA patterns instead")] public partial class ProviderConfiguration : ModuleView, IProviderConfigurationView { /// Occurs when the save button is clicked. diff --git a/DNN Platform/Modules/Journal/DotNetNuke.Modules.Journal.csproj b/DNN Platform/Modules/Journal/DotNetNuke.Modules.Journal.csproj index d181315f90b..751d90e14c6 100644 --- a/DNN Platform/Modules/Journal/DotNetNuke.Modules.Journal.csproj +++ b/DNN Platform/Modules/Journal/DotNetNuke.Modules.Journal.csproj @@ -39,7 +39,9 @@ 4 AllRules.ruleset 1591 - 7 + latest + true + CS0618,SA1600,SA1601,SA1602,SA1614 pdbonly @@ -49,7 +51,9 @@ bin\DotNetNuke.Modules.Journal.XML AllRules.ruleset 1591 - 7 + latest + true + CS0618,SA1600,SA1601,SA1602,SA1614 @@ -67,8 +71,7 @@ ..\..\..\packages\Microsoft.Extensions.DependencyInjection.Abstractions.2.1.1\lib\netstandard2.0\Microsoft.Extensions.DependencyInjection.Abstractions.dll - ..\..\..\packages\Newtonsoft.Json.13.0.2\lib\net45\Newtonsoft.Json.dll - True + ..\..\..\packages\Newtonsoft.Json.13.0.3\lib\net45\Newtonsoft.Json.dll diff --git a/DNN Platform/Modules/Journal/packages.config b/DNN Platform/Modules/Journal/packages.config index a0229fe8927..8b4ec405821 100644 --- a/DNN Platform/Modules/Journal/packages.config +++ b/DNN Platform/Modules/Journal/packages.config @@ -6,6 +6,6 @@ - + \ No newline at end of file diff --git a/DNN Platform/Modules/MemberDirectory/DotNetNuke.Modules.MemberDirectory.csproj b/DNN Platform/Modules/MemberDirectory/DotNetNuke.Modules.MemberDirectory.csproj index 1d90cd50bd6..e11eaa8eab2 100644 --- a/DNN Platform/Modules/MemberDirectory/DotNetNuke.Modules.MemberDirectory.csproj +++ b/DNN Platform/Modules/MemberDirectory/DotNetNuke.Modules.MemberDirectory.csproj @@ -41,7 +41,9 @@ 4 bin\DotNetNuke.Modules.MemberDirectory.XML 1591 - 7 + latest + true + CS0618,SA1600,SA1601,SA1614 pdbonly @@ -52,7 +54,9 @@ 4 bin\DotNetNuke.Modules.MemberDirectory.XML 1591 - 7 + latest + true + CS0618,SA1600,SA1601,SA1614 @@ -64,8 +68,7 @@ ..\..\DotNetNuke.Web.Client\bin\DotNetNuke.Web.Client.dll - ..\..\..\packages\Newtonsoft.Json.13.0.2\lib\net45\Newtonsoft.Json.dll - True + ..\..\..\packages\Newtonsoft.Json.13.0.3\lib\net45\Newtonsoft.Json.dll @@ -171,6 +174,10 @@ + + {5FE5D021-9C8D-47A6-BD34-F328BA3E709C} + DotNetNuke.Internal.SourceGenerators + {6928A9B1-F88A-4581-A132-D3EB38669BB0} DotNetNuke.Abstractions diff --git a/DNN Platform/Modules/MemberDirectory/Presenters/ModuleSettingsPresenter.cs b/DNN Platform/Modules/MemberDirectory/Presenters/ModuleSettingsPresenter.cs index c11d552a0c3..b04062d0cab 100644 --- a/DNN Platform/Modules/MemberDirectory/Presenters/ModuleSettingsPresenter.cs +++ b/DNN Platform/Modules/MemberDirectory/Presenters/ModuleSettingsPresenter.cs @@ -3,18 +3,18 @@ // See the LICENSE file in the project root for more information namespace DotNetNuke.Modules.MemberDirectory.Presenters { - using System; using System.Collections.Generic; - + using DotNetNuke.Common.Lists; using DotNetNuke.Entities.Profile; using DotNetNuke.Entities.Users.Social; + using DotNetNuke.Internal.SourceGenerators; using DotNetNuke.Modules.MemberDirectory.ViewModels; using DotNetNuke.Security.Roles; - using DotNetNuke.Web.Mvp; - - [Obsolete("Deprecated in DNN 9.2.0. Replace WebFormsMvp and DotNetNuke.Web.Mvp with MVC or SPA patterns instead. Scheduled removal in v11.0.0.")] - public class ModuleSettingsPresenter : ModuleSettingsPresenter, MemberDirectorySettingsModel> + using DotNetNuke.Web.Mvp; + + [DnnDeprecated(9, 2, 0, "Replace WebFormsMvp and DotNetNuke.Web.Mvp with MVC or SPA patterns instead")] + public partial class ModuleSettingsPresenter : ModuleSettingsPresenter, MemberDirectorySettingsModel> { /// Initializes a new instance of the class. /// diff --git a/DNN Platform/Modules/MemberDirectory/Settings.ascx.cs b/DNN Platform/Modules/MemberDirectory/Settings.ascx.cs index 863c34475c4..fdf4d1feee4 100644 --- a/DNN Platform/Modules/MemberDirectory/Settings.ascx.cs +++ b/DNN Platform/Modules/MemberDirectory/Settings.ascx.cs @@ -12,18 +12,19 @@ namespace DotNetNuke.Modules.MemberDirectory using System.Web; using System.Web.UI; using System.Web.UI.WebControls; - + using DotNetNuke.Common.Lists; using DotNetNuke.Common.Utilities; using DotNetNuke.Entities.Profile; + using DotNetNuke.Internal.SourceGenerators; using DotNetNuke.Modules.MemberDirectory.Presenters; using DotNetNuke.Modules.MemberDirectory.ViewModels; using DotNetNuke.Services.Localization; using DotNetNuke.Web.Mvp; using DotNetNuke.Web.UI.WebControls.Extensions; - using WebFormsMvp; - - [Obsolete("Deprecated in DNN 9.2.0. Replace WebFormsMvp and DotNetNuke.Web.Mvp with MVC or SPA patterns instead. Scheduled removal in v11.0.0.")] + using WebFormsMvp; + + [DnnDeprecated(9, 2, 0, "Replace WebFormsMvp and DotNetNuke.Web.Mvp with MVC or SPA patterns instead")] [PresenterBinding(typeof(ModuleSettingsPresenter))] public partial class Settings : SettingsView { diff --git a/DNN Platform/Modules/MemberDirectory/ViewModels/MemberDirectorySettingsModel.cs b/DNN Platform/Modules/MemberDirectory/ViewModels/MemberDirectorySettingsModel.cs index 9261ff86a6a..3ba7d653e38 100644 --- a/DNN Platform/Modules/MemberDirectory/ViewModels/MemberDirectorySettingsModel.cs +++ b/DNN Platform/Modules/MemberDirectory/ViewModels/MemberDirectorySettingsModel.cs @@ -4,17 +4,17 @@ namespace DotNetNuke.Modules.MemberDirectory.ViewModels { - using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using DotNetNuke.Entities.Profile; using DotNetNuke.Entities.Users.Social; + using DotNetNuke.Internal.SourceGenerators; using DotNetNuke.Security.Roles; using DotNetNuke.Web.Mvp; - [Obsolete("Deprecated in DNN 9.2.0. Replace WebFormsMvp and DotNetNuke.Web.Mvp with MVC or SPA patterns instead. Scheduled removal in v11.0.0.")] - public class MemberDirectorySettingsModel : SettingsModel + [DnnDeprecated(9, 2, 0, "Replace WebFormsMvp and DotNetNuke.Web.Mvp with MVC or SPA patterns instead")] + public partial class MemberDirectorySettingsModel : SettingsModel { [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Breaking change")] public IList ProfileProperties; diff --git a/DNN Platform/Modules/MemberDirectory/packages.config b/DNN Platform/Modules/MemberDirectory/packages.config index 8a0c1cf2e76..c0323f71eab 100644 --- a/DNN Platform/Modules/MemberDirectory/packages.config +++ b/DNN Platform/Modules/MemberDirectory/packages.config @@ -4,7 +4,7 @@ - + \ No newline at end of file diff --git a/DNN Platform/Modules/RazorHost/AddScript.ascx.cs b/DNN Platform/Modules/RazorHost/AddScript.ascx.cs index 16499ee9f13..bf89968072e 100644 --- a/DNN Platform/Modules/RazorHost/AddScript.ascx.cs +++ b/DNN Platform/Modules/RazorHost/AddScript.ascx.cs @@ -8,13 +8,14 @@ namespace DotNetNuke.Modules.RazorHost using DotNetNuke.Abstractions; using DotNetNuke.Common; + using DotNetNuke.Internal.SourceGenerators; using DotNetNuke.Services.Exceptions; using DotNetNuke.Services.Localization; using DotNetNuke.UI.Modules; using Microsoft.Extensions.DependencyInjection; /// Implements the AddScript view logic. - [Obsolete("Deprecated in 9.3.2, will be removed in 11.0.0, use Razor Pages instead")] + [DnnDeprecated(9, 3, 2, "Use Razor Pages instead")] public partial class AddScript : ModuleUserControlBase { private readonly INavigationManager navigationManager; @@ -27,10 +28,7 @@ public AddScript() } /// - [Obsolete("Deprecated in 9.3.2, will be removed in 11.0.0, use Razor Pages instead")] -#pragma warning disable CS0809 // Obsolete member overrides non-obsolete member protected override void OnInit(EventArgs e) -#pragma warning restore CS0809 // Obsolete member overrides non-obsolete member { base.OnInit(e); @@ -40,10 +38,7 @@ protected override void OnInit(EventArgs e) } /// - [Obsolete("Deprecated in 9.3.2, will be removed in 11.0.0, use Razor Pages instead")] -#pragma warning disable CS0809 // Obsolete member overrides non-obsolete member protected override void OnLoad(EventArgs e) -#pragma warning restore CS0809 // Obsolete member overrides non-obsolete member { base.OnLoad(e); @@ -53,7 +48,6 @@ protected override void OnLoad(EventArgs e) /// Cancel button click event handler. /// The sender of the event. /// The event arguments. - [Obsolete("Deprecated in 9.3.2, will be removed in 11.0.0, use Razor Pages instead")] protected void CmdCancel_Click(object sender, EventArgs e) { try @@ -69,7 +63,6 @@ protected void CmdCancel_Click(object sender, EventArgs e) /// Add button event handler. /// The sender of the event. /// The event arguments. - [Obsolete("Deprecated in 9.3.2, will be removed in 11.0.0, use Razor Pages instead")] protected void CmdAdd_Click(object sender, EventArgs e) { try diff --git a/DNN Platform/Modules/RazorHost/CreateModule.ascx.cs b/DNN Platform/Modules/RazorHost/CreateModule.ascx.cs index 928f133b064..46f031e9630 100644 --- a/DNN Platform/Modules/RazorHost/CreateModule.ascx.cs +++ b/DNN Platform/Modules/RazorHost/CreateModule.ascx.cs @@ -15,6 +15,7 @@ namespace DotNetNuke.Modules.RazorHost using DotNetNuke.Entities.Modules.Definitions; using DotNetNuke.Entities.Tabs; using DotNetNuke.Instrumentation; + using DotNetNuke.Internal.SourceGenerators; using DotNetNuke.Services.Exceptions; using DotNetNuke.Services.FileSystem.Internal; using DotNetNuke.Services.Installer; @@ -24,7 +25,7 @@ namespace DotNetNuke.Modules.RazorHost using Microsoft.Extensions.DependencyInjection; /// Implements the logic for the CreateModule view. - [Obsolete("Deprecated in 9.3.2, will be removed in 11.0.0, use Razor Pages instead")] + [DnnDeprecated(9, 3, 2, "Use Razor Pages instead")] public partial class CreateModule : ModuleUserControlBase { private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(CreateModule)); @@ -40,7 +41,6 @@ public CreateModule() } /// Gets the module control file name without it's extension. - [Obsolete("Deprecated in 9.3.2, will be removed in 11.0.0, use Razor Pages instead")] protected string ModuleControl { get @@ -50,7 +50,6 @@ protected string ModuleControl } /// Gets the razor script path. - [Obsolete("Deprecated in 9.3.2, will be removed in 11.0.0, use Razor Pages instead")] protected string RazorScriptFile { get @@ -67,10 +66,7 @@ protected string RazorScriptFile } /// - [Obsolete("Deprecated in 9.3.2, will be removed in 11.0.0, use Razor Pages instead")] -#pragma warning disable CS0809 // Obsolete member overrides non-obsolete member protected override void OnInit(EventArgs e) -#pragma warning restore CS0809 // Obsolete member overrides non-obsolete member { base.OnInit(e); @@ -80,10 +76,7 @@ protected override void OnInit(EventArgs e) } /// - [Obsolete("Deprecated in 9.3.2, will be removed in 11.0.0, use Razor Pages instead")] -#pragma warning disable CS0809 // Obsolete member overrides non-obsolete member protected override void OnLoad(EventArgs e) -#pragma warning restore CS0809 // Obsolete member overrides non-obsolete member { base.OnLoad(e); diff --git a/DNN Platform/Modules/RazorHost/DotNetNuke.Modules.RazorHost.csproj b/DNN Platform/Modules/RazorHost/DotNetNuke.Modules.RazorHost.csproj index e209b018428..4a4ad6b591f 100644 --- a/DNN Platform/Modules/RazorHost/DotNetNuke.Modules.RazorHost.csproj +++ b/DNN Platform/Modules/RazorHost/DotNetNuke.Modules.RazorHost.csproj @@ -41,7 +41,7 @@ 4 - 7 + latest true @@ -52,7 +52,7 @@ bin\DotNetNuke.Modules.RazorHost.XML - 7 + latest true @@ -195,6 +195,10 @@ + + {5FE5D021-9C8D-47A6-BD34-F328BA3E709C} + DotNetNuke.Internal.SourceGenerators + {6928a9b1-f88a-4581-a132-d3eb38669bb0} DotNetNuke.Abstractions diff --git a/DNN Platform/Modules/RazorHost/EditScript.ascx.cs b/DNN Platform/Modules/RazorHost/EditScript.ascx.cs index bfcdfe88c9d..11865f74b44 100644 --- a/DNN Platform/Modules/RazorHost/EditScript.ascx.cs +++ b/DNN Platform/Modules/RazorHost/EditScript.ascx.cs @@ -11,13 +11,14 @@ namespace DotNetNuke.Modules.RazorHost using DotNetNuke.Common; using DotNetNuke.Common.Utilities; using DotNetNuke.Entities.Modules; + using DotNetNuke.Internal.SourceGenerators; using DotNetNuke.Services.Exceptions; using DotNetNuke.Services.Localization; using DotNetNuke.UI.Modules; using Microsoft.Extensions.DependencyInjection; /// Implements the EditScript view logic. - [Obsolete("Deprecated in 9.3.2, will be removed in 11.0.0, use Razor Pages instead")] + [DnnDeprecated(9, 3, 2, "Use Razor Pages instead")] public partial class EditScript : ModuleUserControlBase { private readonly INavigationManager navigationManager; @@ -31,7 +32,6 @@ public EditScript() } /// Gets the razor script file. - [Obsolete("Deprecated in 9.3.2, will be removed in 11.0.0, use Razor Pages instead")] protected string RazorScriptFile { get @@ -48,10 +48,7 @@ protected string RazorScriptFile } /// - [Obsolete("Deprecated in 9.3.2, will be removed in 11.0.0, use Razor Pages instead")] -#pragma warning disable CS0809 // Obsolete member overrides non-obsolete member protected override void OnInit(EventArgs e) -#pragma warning restore CS0809 // Obsolete member overrides non-obsolete member { base.OnInit(e); @@ -63,10 +60,7 @@ protected override void OnInit(EventArgs e) } /// - [Obsolete("Deprecated in 9.3.2, will be removed in 11.0.0, use Razor Pages instead")] -#pragma warning disable CS0809 // Obsolete member overrides non-obsolete member protected override void OnLoad(EventArgs e) -#pragma warning restore CS0809 // Obsolete member overrides non-obsolete member { base.OnLoad(e); diff --git a/DNN Platform/Modules/RazorHost/RazorHost.ascx.cs b/DNN Platform/Modules/RazorHost/RazorHost.ascx.cs index 42596ab6eaa..bd1ace98d8c 100644 --- a/DNN Platform/Modules/RazorHost/RazorHost.ascx.cs +++ b/DNN Platform/Modules/RazorHost/RazorHost.ascx.cs @@ -3,22 +3,20 @@ // See the LICENSE file in the project root for more information namespace DotNetNuke.Modules.RazorHost { - using System; - using DotNetNuke.Entities.Modules; using DotNetNuke.Entities.Modules.Actions; + using DotNetNuke.Internal.SourceGenerators; using DotNetNuke.Security; using DotNetNuke.Services.Localization; using DotNetNuke.Web.Razor; /// Implements the RazorHost view logic. - [Obsolete("Deprecated in 9.3.2, will be removed in 11.0.0, use Razor Pages instead")] + [DnnDeprecated(9, 3, 2, "Use Razor Pages instead")] public partial class RazorHost : RazorModuleBase, IActionable { private string razorScriptFileFormatString = "~/DesktopModules/RazorModules/RazorHost/Scripts/{0}"; /// - [Obsolete("Deprecated in 9.3.2, will be removed in 11.0.0, use Razor Pages instead")] public ModuleActionCollection ModuleActions { get @@ -51,7 +49,6 @@ public ModuleActionCollection ModuleActions } /// - [Obsolete("Deprecated in 9.3.2, will be removed in 11.0.0, use Razor Pages instead")] protected override string RazorScriptFile { get diff --git a/DNN Platform/Modules/RazorHost/RazorHostSettingsExtensions.cs b/DNN Platform/Modules/RazorHost/RazorHostSettingsExtensions.cs index 98fe1b4ea01..49e8603f214 100644 --- a/DNN Platform/Modules/RazorHost/RazorHostSettingsExtensions.cs +++ b/DNN Platform/Modules/RazorHost/RazorHostSettingsExtensions.cs @@ -4,22 +4,21 @@ namespace DotNetNuke.Modules.RazorHost { - using System; using System.Web.UI; using DotNetNuke.Entities.Modules; + using DotNetNuke.Internal.SourceGenerators; using DotNetNuke.Security; /// Extension methods for the razor host settings. - [Obsolete("Deprecated in 9.3.2, will be removed in 11.0.0, use Razor Pages instead")] - public static class RazorHostSettingsExtensions + [DnnDeprecated(9, 3, 2, "Use Razor Pages instead")] + public static partial class RazorHostSettingsExtensions { /// Loads the razor host settings control. /// The parent user control. /// The module configuration, . /// The local resource file for localization strings. /// Razor Host Settings, . - [Obsolete("Deprecated in 9.3.2, will be removed in 11.0.0, use Razor Pages instead")] public static Settings LoadRazorSettingsControl(this UserControl parent, ModuleInfo configuration, string localResourceFile) { var control = (Settings)parent.LoadControl("~/DesktopModules/RazorModules/RazorHost/Settings.ascx"); diff --git a/DNN Platform/Modules/RazorHost/Settings.ascx.cs b/DNN Platform/Modules/RazorHost/Settings.ascx.cs index 84a4bc8b21d..9a64659942b 100644 --- a/DNN Platform/Modules/RazorHost/Settings.ascx.cs +++ b/DNN Platform/Modules/RazorHost/Settings.ascx.cs @@ -8,18 +8,16 @@ namespace DotNetNuke.Modules.RazorHost using System.Web.UI.WebControls; using DotNetNuke.Entities.Modules; + using DotNetNuke.Internal.SourceGenerators; /// Implements the Settings view logic. - [Obsolete("Deprecated in 9.3.2, will be removed in 11.0.0, use Razor Pages instead")] + [DnnDeprecated(9, 3, 2, "Use Razor Pages instead")] public partial class Settings : ModuleSettingsBase { private string razorScriptFolder = "~/DesktopModules/RazorModules/RazorHost/Scripts/"; /// - [Obsolete("Deprecated in 9.3.2, will be removed in 11.0.0, use Razor Pages instead")] -#pragma warning disable CS0809 // Obsolete member overrides non-obsolete member public override void LoadSettings() -#pragma warning restore CS0809 // Obsolete member overrides non-obsolete member { string basePath = this.Server.MapPath(this.razorScriptFolder); var scriptFileSetting = this.Settings["ScriptFile"] as string; @@ -40,10 +38,7 @@ public override void LoadSettings() } /// - [Obsolete("Deprecated in 9.3.2, will be removed in 11.0.0, use Razor Pages instead")] -#pragma warning disable CS0809 // Obsolete member overrides non-obsolete member public override void UpdateSettings() -#pragma warning restore CS0809 // Obsolete member overrides non-obsolete member { ModuleController.Instance.UpdateModuleSetting(this.ModuleId, "ScriptFile", this.scriptList.SelectedValue); } diff --git a/DNN Platform/Modules/ResourceManager/Dnn.Modules.ResourceManager.csproj b/DNN Platform/Modules/ResourceManager/Dnn.Modules.ResourceManager.csproj index 8191d17fc45..fef5d66c8ff 100644 --- a/DNN Platform/Modules/ResourceManager/Dnn.Modules.ResourceManager.csproj +++ b/DNN Platform/Modules/ResourceManager/Dnn.Modules.ResourceManager.csproj @@ -33,7 +33,7 @@ bin\Dnn.Modules.ResourceManager.xml 1591 AllRules.ruleset - 7 + latest true 4 @@ -46,7 +46,7 @@ bin\Dnn.Modules.ResourceManager.xml 1591 AllRules.ruleset - 7 + latest true 4 @@ -58,8 +58,7 @@ ..\..\..\packages\Microsoft.Extensions.DependencyInjection.Abstractions.2.1.1\lib\netstandard2.0\Microsoft.Extensions.DependencyInjection.Abstractions.dll - ..\..\..\packages\Newtonsoft.Json.13.0.2\lib\net45\Newtonsoft.Json.dll - True + ..\..\..\packages\Newtonsoft.Json.13.0.3\lib\net45\Newtonsoft.Json.dll diff --git a/DNN Platform/Modules/ResourceManager/ResourceManager.Web/package.json b/DNN Platform/Modules/ResourceManager/ResourceManager.Web/package.json index d150254844e..9c92cd9f3b5 100644 --- a/DNN Platform/Modules/ResourceManager/ResourceManager.Web/package.json +++ b/DNN Platform/Modules/ResourceManager/ResourceManager.Web/package.json @@ -26,12 +26,12 @@ "generate": "stencil generate" }, "dependencies": { - "@stencil/core": "^2.18.0" + "@stencil/core": "^2.22.3" }, "license": "MIT", "devDependencies": { "@dnncommunity/dnn-elements": "^0.15.2", - "@stencil/sass": "^2.0.0", - "@stencil/store": "^2.0.1" + "@stencil/sass": "^2.0.4", + "@stencil/store": "^2.0.9" } } diff --git a/DNN Platform/Modules/ResourceManager/ResourceManager.Web/src/components/actions/dnn-action-copy-url/dnn-action-copy-url.tsx b/DNN Platform/Modules/ResourceManager/ResourceManager.Web/src/components/actions/dnn-action-copy-url/dnn-action-copy-url.tsx index b9cec6e4bb8..f16207dc209 100644 --- a/DNN Platform/Modules/ResourceManager/ResourceManager.Web/src/components/actions/dnn-action-copy-url/dnn-action-copy-url.tsx +++ b/DNN Platform/Modules/ResourceManager/ResourceManager.Web/src/components/actions/dnn-action-copy-url/dnn-action-copy-url.tsx @@ -12,8 +12,13 @@ export class DnnActionCopyUrl { @Prop() items!: Item[]; private handleClick(): void { - const url = `${window.location.protocol}//${window.location.host}${this.items[0].path}`; - navigator.clipboard.writeText(url); + let t; + if (this.items[0].path.includes(":")) { + t = this.items[0].path; + } else { + t = `${window.location.protocol}//${window.location.host}${this.items[0].path}`; + } + navigator.clipboard.writeText(t); } render() { diff --git a/DNN Platform/Modules/ResourceManager/ResourceManager.Web/src/components/actions/dnn-action-download-item/dnn-action-download-item.tsx b/DNN Platform/Modules/ResourceManager/ResourceManager.Web/src/components/actions/dnn-action-download-item/dnn-action-download-item.tsx index e77ebe2b38d..deee0b7144e 100644 --- a/DNN Platform/Modules/ResourceManager/ResourceManager.Web/src/components/actions/dnn-action-download-item/dnn-action-download-item.tsx +++ b/DNN Platform/Modules/ResourceManager/ResourceManager.Web/src/components/actions/dnn-action-download-item/dnn-action-download-item.tsx @@ -18,7 +18,7 @@ export class DnnActionDownloadItem { } private handleClick(): void { - this.itemsClient.download(this.item.itemId, true); + this.itemsClient.download(this.item.itemId, false); } render() { diff --git a/DNN Platform/Modules/ResourceManager/ResourceManager.Web/src/services/ItemsClient.ts b/DNN Platform/Modules/ResourceManager/ResourceManager.Web/src/services/ItemsClient.ts index 07007b4af50..87b2c8dbd7d 100644 --- a/DNN Platform/Modules/ResourceManager/ResourceManager.Web/src/services/ItemsClient.ts +++ b/DNN Platform/Modules/ResourceManager/ResourceManager.Web/src/services/ItemsClient.ts @@ -171,6 +171,7 @@ export class ItemsClient{ .then(response => { if (response.status == 200) { var filename = response.headers.get("Content-Disposition").split("filename=")[1]; + filename = this.decodeRFC5987ContentDisposition(filename); response.blob().then(blob => { var oldDownloadLink = document.querySelector("#downloadLink"); if (oldDownloadLink) { @@ -189,6 +190,20 @@ export class ItemsClient{ .catch(error => reject(error)); }); } + private decodeRFC5987ContentDisposition(filename: string): string { + filename = filename.replace(/(^")|("$)/g, ''); + + if (filename.startsWith("=?utf-8?B?") && filename.endsWith("?=")) { + const encoded = filename.slice(10, -2); + return decodeURIComponent( + atob(encoded) + .split('') + .map(c => '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2)) + .join('') + ); + } + return filename; + } public search( folderId: number, @@ -741,3 +756,4 @@ export interface DeleteFolderRequest{ export interface DeleteFileRequest{ FileId: number; } + diff --git a/DNN Platform/Modules/ResourceManager/packages.config b/DNN Platform/Modules/ResourceManager/packages.config index 8b7c2067052..8cf856b82b9 100644 --- a/DNN Platform/Modules/ResourceManager/packages.config +++ b/DNN Platform/Modules/ResourceManager/packages.config @@ -4,6 +4,6 @@ - + \ No newline at end of file diff --git a/DNN Platform/Providers/AuthenticationProviders/DotNetNuke.Authentication.Facebook/DotNetNuke.Authentication.Facebook.csproj b/DNN Platform/Providers/AuthenticationProviders/DotNetNuke.Authentication.Facebook/DotNetNuke.Authentication.Facebook.csproj index 0b794999d82..9f9f9ea9bf6 100644 --- a/DNN Platform/Providers/AuthenticationProviders/DotNetNuke.Authentication.Facebook/DotNetNuke.Authentication.Facebook.csproj +++ b/DNN Platform/Providers/AuthenticationProviders/DotNetNuke.Authentication.Facebook/DotNetNuke.Authentication.Facebook.csproj @@ -41,7 +41,9 @@ 4 1591 bin\DotNetNuke.Authentication.Facebook.XML - 7 + latest + true + CS0618,SA1600 pdbonly @@ -52,7 +54,9 @@ 4 1591 bin\DotNetNuke.Authentication.Facebook.XML - 7 + latest + true + CS0618,SA1600 diff --git a/DNN Platform/Providers/AuthenticationProviders/DotNetNuke.Authentication.Google/DotNetNuke.Authentication.Google.csproj b/DNN Platform/Providers/AuthenticationProviders/DotNetNuke.Authentication.Google/DotNetNuke.Authentication.Google.csproj index 62798a66ddb..5488de3340e 100644 --- a/DNN Platform/Providers/AuthenticationProviders/DotNetNuke.Authentication.Google/DotNetNuke.Authentication.Google.csproj +++ b/DNN Platform/Providers/AuthenticationProviders/DotNetNuke.Authentication.Google/DotNetNuke.Authentication.Google.csproj @@ -41,7 +41,9 @@ 4 bin\DotNetNuke.Authentication.Google.XML 1591 - 7 + latest + true + CS0618,SA1600 pdbonly @@ -52,7 +54,9 @@ 4 bin\DotNetNuke.Authentication.Google.XML 1591 - 7 + latest + true + CS0618,SA1600 diff --git a/DNN Platform/Providers/AuthenticationProviders/DotNetNuke.Authentication.LiveConnect/DotNetNuke.Authentication.LiveConnect.csproj b/DNN Platform/Providers/AuthenticationProviders/DotNetNuke.Authentication.LiveConnect/DotNetNuke.Authentication.LiveConnect.csproj index bef8c71a317..d67f14690ee 100644 --- a/DNN Platform/Providers/AuthenticationProviders/DotNetNuke.Authentication.LiveConnect/DotNetNuke.Authentication.LiveConnect.csproj +++ b/DNN Platform/Providers/AuthenticationProviders/DotNetNuke.Authentication.LiveConnect/DotNetNuke.Authentication.LiveConnect.csproj @@ -41,7 +41,9 @@ 4 1591 bin\DotNetNuke.Authentication.LiveConnect.XML - 7 + latest + true + CS0618,SA1600 pdbonly @@ -52,7 +54,9 @@ 4 1591 bin\DotNetNuke.Authentication.LiveConnect.XML - 7 + latest + true + CS0618,SA1600 diff --git a/DNN Platform/Providers/AuthenticationProviders/DotNetNuke.Authentication.Twitter/DotNetNuke.Authentication.Twitter.csproj b/DNN Platform/Providers/AuthenticationProviders/DotNetNuke.Authentication.Twitter/DotNetNuke.Authentication.Twitter.csproj index 8f0ec385705..544b8ddc935 100644 --- a/DNN Platform/Providers/AuthenticationProviders/DotNetNuke.Authentication.Twitter/DotNetNuke.Authentication.Twitter.csproj +++ b/DNN Platform/Providers/AuthenticationProviders/DotNetNuke.Authentication.Twitter/DotNetNuke.Authentication.Twitter.csproj @@ -41,7 +41,9 @@ 4 bin\DotNetNuke.Authentication.Twitter.XML 1591 - 7 + latest + true + CS0618,SA1600 pdbonly @@ -52,7 +54,9 @@ 4 1591 bin\DotNetNuke.Authentication.Twitter.XML - 7 + latest + true + CS0618,SA1600 diff --git a/DNN Platform/Providers/CachingProviders/DotNetNuke.Providers.Caching.SimpleWebFarmCachingProvider/DotNetNuke.Providers.Caching.SimpleWebFarmCachingProvider.csproj b/DNN Platform/Providers/CachingProviders/DotNetNuke.Providers.Caching.SimpleWebFarmCachingProvider/DotNetNuke.Providers.Caching.SimpleWebFarmCachingProvider.csproj index 8f73eb686cd..4da4f0b5a22 100644 --- a/DNN Platform/Providers/CachingProviders/DotNetNuke.Providers.Caching.SimpleWebFarmCachingProvider/DotNetNuke.Providers.Caching.SimpleWebFarmCachingProvider.csproj +++ b/DNN Platform/Providers/CachingProviders/DotNetNuke.Providers.Caching.SimpleWebFarmCachingProvider/DotNetNuke.Providers.Caching.SimpleWebFarmCachingProvider.csproj @@ -26,7 +26,8 @@ 4 bin\Providers\DotNetNuke.Providers.Caching.SimpleWebFarmCachingProvider.xml 1591,0618 - 7 + latest + true pdbonly @@ -37,7 +38,8 @@ 4 bin\Providers\DotNetNuke.Providers.Caching.SimpleWebFarmCachingProvider.xml 1591,0618 - 7 + latest + true diff --git a/DNN Platform/Providers/ClientCapabilityProviders/Provider.AspNetCCP/DotNetNuke.Providers.AspNetCCP.csproj b/DNN Platform/Providers/ClientCapabilityProviders/Provider.AspNetCCP/DotNetNuke.Providers.AspNetCCP.csproj index 3540355369c..1513c8f2c05 100644 --- a/DNN Platform/Providers/ClientCapabilityProviders/Provider.AspNetCCP/DotNetNuke.Providers.AspNetCCP.csproj +++ b/DNN Platform/Providers/ClientCapabilityProviders/Provider.AspNetCCP/DotNetNuke.Providers.AspNetCCP.csproj @@ -24,7 +24,7 @@ 4 bin\Providers\DotNetNuke.Providers.AspNetClientCapabilityProvider.xml 1591,0618 - 7 + latest pdbonly @@ -34,7 +34,7 @@ bin\Providers\DotNetNuke.Providers.AspNetClientCapabilityProvider.xml prompt 1591,0618 - 7 + latest true @@ -44,7 +44,7 @@ 4 bin\Providers\DotNetNuke.Providers.AspNetClientCapabilityProvider.xml 1591,0618 - 7 + latest pdbonly @@ -54,7 +54,7 @@ bin\Providers\DotNetNuke.Providers.AspNetClientCapabilityProvider.xml prompt 1591,0618 - 7 + latest diff --git a/DNN Platform/Providers/ClientCapabilityProviders/Provider.AspNetCCP/Properties/RetailerConstants.cs b/DNN Platform/Providers/ClientCapabilityProviders/Provider.AspNetCCP/Properties/RetailerConstants.cs index 14b67fcda27..82d18c9d0b3 100644 --- a/DNN Platform/Providers/ClientCapabilityProviders/Provider.AspNetCCP/Properties/RetailerConstants.cs +++ b/DNN Platform/Providers/ClientCapabilityProviders/Provider.AspNetCCP/Properties/RetailerConstants.cs @@ -16,11 +16,11 @@ public static class RetailerConstants #pragma warning disable SA1310 // Field should not contain an underscore /// The url to send purchasers to. - [Obsolete("Deprecated in Platform 9.8.1. Use RetailerUrl instead. Scheduled removal in v11.0.0.")] + [Obsolete("Deprecated in DotNetNuke 9.8.1. Use RetailerUrl instead. Scheduled removal in v11.0.0.")] public const string RETAILER_URL = RetailerUrl; /// The name of the retailer. - [Obsolete("Deprecated in Platform 9.8.1. Use RetailerName instead. Scheduled removal in v11.0.0.")] + [Obsolete("Deprecated in DotNetNuke 9.8.1. Use RetailerName instead. Scheduled removal in v11.0.0.")] public const string RETAILER_NAME = RetailerName; #pragma warning restore SA1310 // Field should not contain an underscore } diff --git a/DNN Platform/Providers/FolderProviders/AzureFolderProvider/Settings.ascx.cs b/DNN Platform/Providers/FolderProviders/AzureFolderProvider/Settings.ascx.cs index 9243dba9e66..5270749d39c 100644 --- a/DNN Platform/Providers/FolderProviders/AzureFolderProvider/Settings.ascx.cs +++ b/DNN Platform/Providers/FolderProviders/AzureFolderProvider/Settings.ascx.cs @@ -2,391 +2,396 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information -namespace DotNetNuke.Providers.FolderProviders.AzureFolderProvider -{ - using System; - using System.Collections; - using System.Linq; - using System.Web.UI.WebControls; - - using DotNetNuke.Instrumentation; - using DotNetNuke.Services.FileSystem; - using DotNetNuke.Services.Localization; - using Microsoft.WindowsAzure.Storage; - using Microsoft.WindowsAzure.Storage.Auth; - using Microsoft.WindowsAzure.Storage.Blob; - - /// Windows Azure Storage Settings Control. - public partial class Settings : FolderMappingSettingsControlBase - { +namespace DotNetNuke.Providers.FolderProviders.AzureFolderProvider +{ + using System; + using System.Collections; + using System.Diagnostics.CodeAnalysis; + using System.Linq; + using System.Web.UI.WebControls; + + using DotNetNuke.Instrumentation; + using DotNetNuke.Services.FileSystem; + using DotNetNuke.Services.Localization; + using Microsoft.WindowsAzure.Storage; + using Microsoft.WindowsAzure.Storage.Auth; + using Microsoft.WindowsAzure.Storage.Blob; + + /// Windows Azure Storage Settings Control. + public partial class Settings : FolderMappingSettingsControlBase + { private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(Settings)); - /// Loads concrete settings. - /// The Hashtable containing the folder mapping settings. - public override void LoadSettings(Hashtable folderMappingSettings) - { - var folderProvider = FolderProvider.Instance(Constants.FolderProviderType); - if (folderMappingSettings.ContainsKey(Constants.AccountName)) - { - this.tbAccountName.Text = folderProvider.GetEncryptedSetting(folderMappingSettings, Constants.AccountName); - } - - if (folderMappingSettings.ContainsKey(Constants.AccountKey)) - { - this.tbAccountKey.Text = folderProvider.GetEncryptedSetting(folderMappingSettings, Constants.AccountKey); - } - - if (this.tbAccountName.Text.Length > 0 && this.tbAccountKey.Text.Length > 0) - { - var bucketName = string.Empty; - - if (folderMappingSettings.ContainsKey(Constants.Container)) - { - bucketName = folderMappingSettings[Constants.Container].ToString(); - } - - this.LoadContainers(); - - var bucket = this.ddlContainers.Items.FindByText(bucketName); - - if (bucket != null) - { - this.ddlContainers.SelectedIndex = this.ddlContainers.Items.IndexOf(bucket); - } - } - - if (folderMappingSettings.ContainsKey(Constants.UseHttps)) - { - this.chkUseHttps.Checked = bool.Parse(folderMappingSettings[Constants.UseHttps].ToString()); - } - - this.chkDirectLink.Checked = !folderMappingSettings.ContainsKey(Constants.DirectLink) || folderMappingSettings[Constants.DirectLink].ToString().ToLowerInvariant() == "true"; - - if (folderMappingSettings.ContainsKey(Constants.CustomDomain)) - { - this.tbCustomDomain.Text = folderProvider.GetEncryptedSetting(folderMappingSettings, Constants.CustomDomain); - } - - if (folderMappingSettings.ContainsKey(Constants.SyncBatchSize) && folderMappingSettings[Constants.SyncBatchSize] != null) - { - this.tbSyncBatchSize.Text = folderMappingSettings[Constants.SyncBatchSize].ToString(); - } - else - { - this.tbSyncBatchSize.Text = Constants.DefaultSyncBatchSize.ToString(); - } + /// Loads concrete settings. + /// The Hashtable containing the folder mapping settings. + public override void LoadSettings(Hashtable folderMappingSettings) + { + var folderProvider = FolderProvider.Instance(Constants.FolderProviderType); + if (folderMappingSettings.ContainsKey(Constants.AccountName)) + { + this.tbAccountName.Text = folderProvider.GetEncryptedSetting(folderMappingSettings, Constants.AccountName); + } + + if (folderMappingSettings.ContainsKey(Constants.AccountKey)) + { + this.tbAccountKey.Text = folderProvider.GetEncryptedSetting(folderMappingSettings, Constants.AccountKey); + } + + if (this.tbAccountName.Text.Length > 0 && this.tbAccountKey.Text.Length > 0) + { + var bucketName = string.Empty; + + if (folderMappingSettings.ContainsKey(Constants.Container)) + { + bucketName = folderMappingSettings[Constants.Container].ToString(); + } + + this.LoadContainers(); + + var bucket = this.ddlContainers.Items.FindByText(bucketName); + + if (bucket != null) + { + this.ddlContainers.SelectedIndex = this.ddlContainers.Items.IndexOf(bucket); + } + } + + if (folderMappingSettings.ContainsKey(Constants.UseHttps)) + { + this.chkUseHttps.Checked = bool.Parse(folderMappingSettings[Constants.UseHttps].ToString()); + } + + this.chkDirectLink.Checked = !folderMappingSettings.ContainsKey(Constants.DirectLink) || folderMappingSettings[Constants.DirectLink].ToString().ToLowerInvariant() == "true"; + + if (folderMappingSettings.ContainsKey(Constants.CustomDomain)) + { + this.tbCustomDomain.Text = folderProvider.GetEncryptedSetting(folderMappingSettings, Constants.CustomDomain); + } + + if (folderMappingSettings.ContainsKey(Constants.SyncBatchSize) && folderMappingSettings[Constants.SyncBatchSize] != null) + { + this.tbSyncBatchSize.Text = folderMappingSettings[Constants.SyncBatchSize].ToString(); + } + else + { + this.tbSyncBatchSize.Text = Constants.DefaultSyncBatchSize.ToString(); + } } - /// Updates concrete settings for the specified folder mapping. - /// The folder mapping identifier. - public override void UpdateSettings(int folderMappingID) - { - this.Page.Validate(); - - if (!this.Page.IsValid) - { - throw new Exception(); - } - - var folderMappingController = FolderMappingController.Instance; - var folderMapping = folderMappingController.GetFolderMapping(folderMappingID); - - var accountName = this.GetAccountName(); - var accountKey = this.GetAccountKey(); - var container = this.GetContainer(); - var useHttps = this.GetUseHttps(); - var customDomain = this.GetCustomDomain(); - var synchBatchSize = this.GetSynchBatchSize(); - - if (AreThereFolderMappingsWithSameSettings(folderMapping, accountName, container)) - { - this.valContainerName.ErrorMessage = Localization.GetString("MultipleFolderMappingsWithSameSettings.ErrorMessage", this.LocalResourceFile); - this.valContainerName.IsValid = false; - - throw new Exception(); - } - - folderMapping.FolderMappingSettings[Constants.AccountName] = accountName; - folderMapping.FolderMappingSettings[Constants.AccountKey] = accountKey; - folderMapping.FolderMappingSettings[Constants.Container] = container; - folderMapping.FolderMappingSettings[Constants.UseHttps] = useHttps; - folderMapping.FolderMappingSettings[Constants.DirectLink] = this.chkDirectLink.Checked; - folderMapping.FolderMappingSettings[Constants.CustomDomain] = customDomain; - folderMapping.FolderMappingSettings[Constants.SyncBatchSize] = synchBatchSize; - - folderMappingController.UpdateFolderMapping(folderMapping); - } - - /// - /// - protected void DdlContainers_SelectedIndexChanged(object sender, EventArgs e) - { - if (this.ddlContainers.SelectedIndex != 1) - { - return; - } - - if (this.tbAccountName.Text.Trim().Length > 0 && this.tbAccountKey.Text.Trim().Length > 0) - { - this.ddlContainers.Items.Clear(); - - this.ddlContainers.Items.Add(Localization.GetString("SelectContainer", this.LocalResourceFile)); - this.ddlContainers.Items.Add(Localization.GetString("RefreshContainerList", this.LocalResourceFile)); - - this.LoadContainers(); - - if (this.ddlContainers.Items.Count == 3) - { - // If there is only one container, then select it - this.ddlContainers.SelectedValue = this.ddlContainers.Items[2].Value; - } - } - else - { - this.valContainerName.ErrorMessage = Localization.GetString("CredentialsRequired.ErrorMessage", this.LocalResourceFile); - this.valContainerName.IsValid = false; - } - } - - /// - /// - protected void BtnNewContainer_Click(object sender, EventArgs e) - { - this.SelectContainerPanel.Visible = false; - this.CreateContainerPanel.Visible = true; - } - - /// - /// - protected void BtnSelectExistingContainer_Click(object sender, EventArgs e) - { - this.SelectContainerPanel.Visible = true; - this.CreateContainerPanel.Visible = false; - } - - /// - /// - protected void ValContainerName_ServerValidate(object source, ServerValidateEventArgs args) - { - if (this.SelectContainerPanel.Visible) - { - if (this.ddlContainers.SelectedIndex > 1) - { - args.IsValid = true; - return; - } - } - else - { - if (this.tbContainerName.Text.Trim().Length > 0) - { - args.IsValid = true; - return; - } - } - - this.valContainerName.ErrorMessage = Localization.GetString("valContainerName.ErrorMessage", this.LocalResourceFile); - args.IsValid = false; - } - - private static bool AreThereFolderMappingsWithSameSettings(FolderMappingInfo folderMapping, string accountName, string container) - { - var folderMappingController = FolderMappingController.Instance; - var folderMappings = folderMappingController.GetFolderMappings(folderMapping.PortalID); - - return folderMappings - .Where(fm => fm.FolderMappingID != folderMapping.FolderMappingID && fm.FolderProviderType == folderMapping.FolderProviderType) - .Any(fm => fm.FolderMappingSettings[Constants.AccountName].ToString().Equals(accountName, StringComparison.InvariantCulture) && - fm.FolderMappingSettings[Constants.Container].ToString().Equals(container, StringComparison.InvariantCultureIgnoreCase)); - } - - private string GetUseHttps() - { - return this.chkUseHttps.Checked.ToString(); - } - - private string GetContainer() - { - string container; - - if (this.SelectContainerPanel.Visible) - { - container = this.ddlContainers.SelectedValue; - } - else - { - container = this.tbContainerName.Text.Trim().ToLowerInvariant(); - if (!this.CreateContainer(container)) - { - throw new Exception(); - } - } - - return container; - } - - private bool CreateContainer(string containerName) - { - var accountName = this.tbAccountName.Text.Trim(); - var accountKey = this.tbAccountKey.Text.Trim(); - var useHttps = this.chkUseHttps.Checked; - - StorageCredentials sc; - - try - { - sc = new StorageCredentials(accountName, accountKey); - } - catch (Exception ex) - { - Logger.Error(ex); - - this.valContainerName.ErrorMessage = Localization.GetString("AuthenticationFailure.ErrorMessage", this.LocalResourceFile); - this.valContainerName.IsValid = false; - - return false; - } - - var csa = new CloudStorageAccount(sc, useHttps); - var blobClient = csa.CreateCloudBlobClient(); - var container = blobClient.GetContainerReference(containerName); - - try - { - if (container.CreateIfNotExists()) - { - var permissions = container.GetPermissions(); - permissions.PublicAccess = BlobContainerPublicAccessType.Container; - container.SetPermissions(permissions); - } - - return true; - } - catch (StorageException ex) - { - if (ex.RequestInformation.ExtendedErrorInformation != null) - { - switch (ex.RequestInformation.ExtendedErrorInformation.ErrorCode) - { - case "AccountNotFound": - this.valContainerName.ErrorMessage = Localization.GetString( - "AccountNotFound.ErrorMessage", - this.LocalResourceFile); - break; - case "AuthenticationFailure": - this.valContainerName.ErrorMessage = Localization.GetString( - "AuthenticationFailure.ErrorMessage", this.LocalResourceFile); - break; - case "AccessDenied": - this.valContainerName.ErrorMessage = Localization.GetString( - "AccessDenied.ErrorMessage", - this.LocalResourceFile); - break; - case "ContainerAlreadyExists": - return true; - default: - Logger.Error(ex); - this.valContainerName.ErrorMessage = Localization.GetString( - "NewContainer.ErrorMessage", - this.LocalResourceFile); - break; - } - } - else - { - this.valContainerName.ErrorMessage = ex.RequestInformation.HttpStatusMessage ?? ex.Message; - } - } - catch (Exception ex) - { - Logger.Error(ex); - this.valContainerName.ErrorMessage = Localization.GetString("NewContainer.ErrorMessage", this.LocalResourceFile); - } - - this.valContainerName.IsValid = false; - return false; - } - - private string GetAccountKey() - { - return FolderProvider.Instance(Constants.FolderProviderType).EncryptValue(this.tbAccountKey.Text); - } - - private string GetAccountName() - { - return FolderProvider.Instance(Constants.FolderProviderType).EncryptValue(this.tbAccountName.Text); - } - - private string GetCustomDomain() - { - return FolderProvider.Instance(Constants.FolderProviderType).EncryptValue(this.tbCustomDomain.Text); - } - - private string GetSynchBatchSize() - { - return this.tbSyncBatchSize.Text; - } - - private void LoadContainers() - { - var accountName = this.tbAccountName.Text.Trim(); - var accountKey = this.tbAccountKey.Text.Trim(); - var useHttps = this.chkUseHttps.Checked; - - StorageCredentials sc; - - try - { - sc = new StorageCredentials(accountName, accountKey); - } - catch (Exception ex) - { - Logger.Error(ex); - - this.valContainerName.ErrorMessage = Localization.GetString("AuthenticationFailure.ErrorMessage", this.LocalResourceFile); - this.valContainerName.IsValid = false; - - return; - } - - var csa = new CloudStorageAccount(sc, useHttps); - var blobClient = csa.CreateCloudBlobClient(); - - try - { - foreach (var container in blobClient.ListContainers()) - { - this.ddlContainers.Items.Add(container.Name); - } - } - catch (StorageException ex) - { - if (ex.RequestInformation.ExtendedErrorInformation != null) - { - switch (ex.RequestInformation.ExtendedErrorInformation.ErrorCode) - { - case "AuthenticationFailure": - this.valContainerName.ErrorMessage = Localization.GetString("AuthenticationFailure.ErrorMessage", this.LocalResourceFile); - break; - default: - Logger.Error(ex); - this.valContainerName.ErrorMessage = Localization.GetString("ListContainers.ErrorMessage", this.LocalResourceFile); - break; - } - } - else - { - this.valContainerName.ErrorMessage = ex.RequestInformation.HttpStatusMessage ?? ex.Message; - } - - this.valContainerName.IsValid = false; - } - catch (Exception ex) - { - Logger.Error(ex); - this.valContainerName.ErrorMessage = Localization.GetString("ListContainers.ErrorMessage", this.LocalResourceFile); - this.valContainerName.IsValid = false; - } - } - } -} + /// Updates concrete settings for the specified folder mapping. + /// The folder mapping identifier. + public override void UpdateSettings(int folderMappingID) + { + this.Page.Validate(); + + if (!this.Page.IsValid) + { + throw new Exception(); + } + + var folderMappingController = FolderMappingController.Instance; + var folderMapping = folderMappingController.GetFolderMapping(folderMappingID); + + var accountName = this.GetAccountName(); + var accountKey = this.GetAccountKey(); + var container = this.GetContainer(); + var useHttps = this.GetUseHttps(); + var customDomain = this.GetCustomDomain(); + var synchBatchSize = this.GetSynchBatchSize(); + + if (AreThereFolderMappingsWithSameSettings(folderMapping, accountName, container)) + { + this.valContainerName.ErrorMessage = Localization.GetString("MultipleFolderMappingsWithSameSettings.ErrorMessage", this.LocalResourceFile); + this.valContainerName.IsValid = false; + + throw new Exception(); + } + + folderMapping.FolderMappingSettings[Constants.AccountName] = accountName; + folderMapping.FolderMappingSettings[Constants.AccountKey] = accountKey; + folderMapping.FolderMappingSettings[Constants.Container] = container; + folderMapping.FolderMappingSettings[Constants.UseHttps] = useHttps; + folderMapping.FolderMappingSettings[Constants.DirectLink] = this.chkDirectLink.Checked; + folderMapping.FolderMappingSettings[Constants.CustomDomain] = customDomain; + folderMapping.FolderMappingSettings[Constants.SyncBatchSize] = synchBatchSize; + + folderMappingController.UpdateFolderMapping(folderMapping); + } + + /// + /// + [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1300:ElementMustBeginWithUpperCaseLetter", Justification = "Breaking Change")] + protected void ddlContainers_SelectedIndexChanged(object sender, EventArgs e) + { + if (this.ddlContainers.SelectedIndex != 1) + { + return; + } + + if (this.tbAccountName.Text.Trim().Length > 0 && this.tbAccountKey.Text.Trim().Length > 0) + { + this.ddlContainers.Items.Clear(); + + this.ddlContainers.Items.Add(Localization.GetString("SelectContainer", this.LocalResourceFile)); + this.ddlContainers.Items.Add(Localization.GetString("RefreshContainerList", this.LocalResourceFile)); + + this.LoadContainers(); + + if (this.ddlContainers.Items.Count == 3) + { + // If there is only one container, then select it + this.ddlContainers.SelectedValue = this.ddlContainers.Items[2].Value; + } + } + else + { + this.valContainerName.ErrorMessage = Localization.GetString("CredentialsRequired.ErrorMessage", this.LocalResourceFile); + this.valContainerName.IsValid = false; + } + } + + /// + /// + [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1300:ElementMustBeginWithUpperCaseLetter", Justification = "Breaking Change")] + protected void btnNewContainer_Click(object sender, EventArgs e) + { + this.SelectContainerPanel.Visible = false; + this.CreateContainerPanel.Visible = true; + } + + /// + /// + [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1300:ElementMustBeginWithUpperCaseLetter", Justification = "Breaking Change")] + protected void btnSelectExistingContainer_Click(object sender, EventArgs e) + { + this.SelectContainerPanel.Visible = true; + this.CreateContainerPanel.Visible = false; + } + + /// + /// + [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1300:ElementMustBeginWithUpperCaseLetter", Justification = "Breaking Change")] + protected void valContainerName_ServerValidate(object source, ServerValidateEventArgs args) + { + if (this.SelectContainerPanel.Visible) + { + if (this.ddlContainers.SelectedIndex > 1) + { + args.IsValid = true; + return; + } + } + else + { + if (this.tbContainerName.Text.Trim().Length > 0) + { + args.IsValid = true; + return; + } + } + + this.valContainerName.ErrorMessage = Localization.GetString("valContainerName.ErrorMessage", this.LocalResourceFile); + args.IsValid = false; + } + + private static bool AreThereFolderMappingsWithSameSettings(FolderMappingInfo folderMapping, string accountName, string container) + { + var folderMappingController = FolderMappingController.Instance; + var folderMappings = folderMappingController.GetFolderMappings(folderMapping.PortalID); + + return folderMappings + .Where(fm => fm.FolderMappingID != folderMapping.FolderMappingID && fm.FolderProviderType == folderMapping.FolderProviderType) + .Any(fm => fm.FolderMappingSettings[Constants.AccountName].ToString().Equals(accountName, StringComparison.InvariantCulture) && + fm.FolderMappingSettings[Constants.Container].ToString().Equals(container, StringComparison.InvariantCultureIgnoreCase)); + } + + private string GetUseHttps() + { + return this.chkUseHttps.Checked.ToString(); + } + + private string GetContainer() + { + string container; + + if (this.SelectContainerPanel.Visible) + { + container = this.ddlContainers.SelectedValue; + } + else + { + container = this.tbContainerName.Text.Trim().ToLowerInvariant(); + if (!this.CreateContainer(container)) + { + throw new Exception(); + } + } + + return container; + } + + private bool CreateContainer(string containerName) + { + var accountName = this.tbAccountName.Text.Trim(); + var accountKey = this.tbAccountKey.Text.Trim(); + var useHttps = this.chkUseHttps.Checked; + + StorageCredentials sc; + + try + { + sc = new StorageCredentials(accountName, accountKey); + } + catch (Exception ex) + { + Logger.Error(ex); + + this.valContainerName.ErrorMessage = Localization.GetString("AuthenticationFailure.ErrorMessage", this.LocalResourceFile); + this.valContainerName.IsValid = false; + + return false; + } + + var csa = new CloudStorageAccount(sc, useHttps); + var blobClient = csa.CreateCloudBlobClient(); + var container = blobClient.GetContainerReference(containerName); + + try + { + if (container.CreateIfNotExists()) + { + var permissions = container.GetPermissions(); + permissions.PublicAccess = BlobContainerPublicAccessType.Container; + container.SetPermissions(permissions); + } + + return true; + } + catch (StorageException ex) + { + if (ex.RequestInformation.ExtendedErrorInformation != null) + { + switch (ex.RequestInformation.ExtendedErrorInformation.ErrorCode) + { + case "AccountNotFound": + this.valContainerName.ErrorMessage = Localization.GetString( + "AccountNotFound.ErrorMessage", + this.LocalResourceFile); + break; + case "AuthenticationFailure": + this.valContainerName.ErrorMessage = Localization.GetString( + "AuthenticationFailure.ErrorMessage", this.LocalResourceFile); + break; + case "AccessDenied": + this.valContainerName.ErrorMessage = Localization.GetString( + "AccessDenied.ErrorMessage", + this.LocalResourceFile); + break; + case "ContainerAlreadyExists": + return true; + default: + Logger.Error(ex); + this.valContainerName.ErrorMessage = Localization.GetString( + "NewContainer.ErrorMessage", + this.LocalResourceFile); + break; + } + } + else + { + this.valContainerName.ErrorMessage = ex.RequestInformation.HttpStatusMessage ?? ex.Message; + } + } + catch (Exception ex) + { + Logger.Error(ex); + this.valContainerName.ErrorMessage = Localization.GetString("NewContainer.ErrorMessage", this.LocalResourceFile); + } + + this.valContainerName.IsValid = false; + return false; + } + + private string GetAccountKey() + { + return FolderProvider.Instance(Constants.FolderProviderType).EncryptValue(this.tbAccountKey.Text); + } + + private string GetAccountName() + { + return FolderProvider.Instance(Constants.FolderProviderType).EncryptValue(this.tbAccountName.Text); + } + + private string GetCustomDomain() + { + return FolderProvider.Instance(Constants.FolderProviderType).EncryptValue(this.tbCustomDomain.Text); + } + + private string GetSynchBatchSize() + { + return this.tbSyncBatchSize.Text; + } + + private void LoadContainers() + { + var accountName = this.tbAccountName.Text.Trim(); + var accountKey = this.tbAccountKey.Text.Trim(); + var useHttps = this.chkUseHttps.Checked; + + StorageCredentials sc; + + try + { + sc = new StorageCredentials(accountName, accountKey); + } + catch (Exception ex) + { + Logger.Error(ex); + + this.valContainerName.ErrorMessage = Localization.GetString("AuthenticationFailure.ErrorMessage", this.LocalResourceFile); + this.valContainerName.IsValid = false; + + return; + } + + var csa = new CloudStorageAccount(sc, useHttps); + var blobClient = csa.CreateCloudBlobClient(); + + try + { + foreach (var container in blobClient.ListContainers()) + { + this.ddlContainers.Items.Add(container.Name); + } + } + catch (StorageException ex) + { + if (ex.RequestInformation.ExtendedErrorInformation != null) + { + switch (ex.RequestInformation.ExtendedErrorInformation.ErrorCode) + { + case "AuthenticationFailure": + this.valContainerName.ErrorMessage = Localization.GetString("AuthenticationFailure.ErrorMessage", this.LocalResourceFile); + break; + default: + Logger.Error(ex); + this.valContainerName.ErrorMessage = Localization.GetString("ListContainers.ErrorMessage", this.LocalResourceFile); + break; + } + } + else + { + this.valContainerName.ErrorMessage = ex.RequestInformation.HttpStatusMessage ?? ex.Message; + } + + this.valContainerName.IsValid = false; + } + catch (Exception ex) + { + Logger.Error(ex); + this.valContainerName.ErrorMessage = Localization.GetString("ListContainers.ErrorMessage", this.LocalResourceFile); + this.valContainerName.IsValid = false; + } + } + } +} diff --git a/DNN Platform/Providers/FolderProviders/DotNetNuke.Providers.FolderProviders.csproj b/DNN Platform/Providers/FolderProviders/DotNetNuke.Providers.FolderProviders.csproj index 4c978b4545c..603c41ac7bb 100644 --- a/DNN Platform/Providers/FolderProviders/DotNetNuke.Providers.FolderProviders.csproj +++ b/DNN Platform/Providers/FolderProviders/DotNetNuke.Providers.FolderProviders.csproj @@ -33,8 +33,10 @@ prompt 4 bin\Providers\DotNetNuke.Providers.FolderProviders.XML - 7 + latest 1591 + true + CS0618,SA1600,SA1606,SA1611 pdbonly @@ -45,7 +47,9 @@ 4 bin\Providers\DotNetNuke.Providers.FolderProviders.XML 1591 - 7 + latest + true + CS0618,SA1600,SA1606,SA1611 true @@ -56,7 +60,7 @@ prompt 4 bin\Providers\DotNetNuke.Providers.FolderProviders.XML - 7 + latest 1591 @@ -68,7 +72,7 @@ 4 bin\Providers\DotNetNuke.Providers.FolderProviders.XML 1591 - 7 + latest diff --git a/DNN Platform/Providers/HtmlEditorProviders/DNNConnect.CKE/App_LocalResources/Options.aspx.resx b/DNN Platform/Providers/HtmlEditorProviders/DNNConnect.CKE/App_LocalResources/Options.aspx.resx index 0a8a9ebfb0a..faca896f4ad 100644 --- a/DNN Platform/Providers/HtmlEditorProviders/DNNConnect.CKE/App_LocalResources/Options.aspx.resx +++ b/DNN Platform/Providers/HtmlEditorProviders/DNNConnect.CKE/App_LocalResources/Options.aspx.resx @@ -533,4 +533,10 @@ Default Upload Folder for images for all portals (overrides setting below) + + Allow users with folder permissions + + + Allow folder users + \ No newline at end of file diff --git a/DNN Platform/Providers/HtmlEditorProviders/DNNConnect.CKE/Browser/Browser.comb.css.bundle b/DNN Platform/Providers/HtmlEditorProviders/DNNConnect.CKE/Browser/Browser.comb.css.bundle index 6135206ea75..dc5d60bf28f 100644 --- a/DNN Platform/Providers/HtmlEditorProviders/DNNConnect.CKE/Browser/Browser.comb.css.bundle +++ b/DNN Platform/Providers/HtmlEditorProviders/DNNConnect.CKE/Browser/Browser.comb.css.bundle @@ -3,7 +3,7 @@ true - + false true diff --git a/DNN Platform/Providers/HtmlEditorProviders/DNNConnect.CKE/CKEditorOptions.ascx b/DNN Platform/Providers/HtmlEditorProviders/DNNConnect.CKE/CKEditorOptions.ascx index 2634738e8b4..546924d8f70 100644 --- a/DNN Platform/Providers/HtmlEditorProviders/DNNConnect.CKE/CKEditorOptions.ascx +++ b/DNN Platform/Providers/HtmlEditorProviders/DNNConnect.CKE/CKEditorOptions.ascx @@ -128,6 +128,10 @@ +
      + Allow folder users + +
      File Browser Security diff --git a/DNN Platform/Providers/HtmlEditorProviders/DNNConnect.CKE/CKEditorOptions.ascx.cs b/DNN Platform/Providers/HtmlEditorProviders/DNNConnect.CKE/CKEditorOptions.ascx.cs index 68ace6afc2d..fa65be15817 100644 --- a/DNN Platform/Providers/HtmlEditorProviders/DNNConnect.CKE/CKEditorOptions.ascx.cs +++ b/DNN Platform/Providers/HtmlEditorProviders/DNNConnect.CKE/CKEditorOptions.ascx.cs @@ -880,6 +880,8 @@ var codeMirrorInfo in this.ConfigUrl.Url = this.ReFormatURL(importedSettings.Config.CustomConfig); } + this.BrowAllowFollowPerms.Checked = importedSettings.BrowserAllowFollowFolderPerms; + if (!string.IsNullOrEmpty(importedSettings.BrowserRoles)) { string sRoles = importedSettings.BrowserRoles; @@ -2435,6 +2437,8 @@ var codeMirrorInfo in moduleController.UpdateModuleSetting(this.ModuleId, $"{key}{SettingConstants.HEIGHT}", this.txtWidth.Text); } + moduleController.UpdateModuleSetting(this.ModuleId, $"{key}{SettingConstants.BROWSERALLOWFOLLOWFOLDERPERMS}", this.BrowAllowFollowPerms.Checked.ToString()); + moduleController.UpdateModuleSetting(this.ModuleId, $"{key}{SettingConstants.BLANKTEXT}", this.txtBlanktext.Text); moduleController.UpdateModuleSetting(this.ModuleId, $"{key}{SettingConstants.CSS}", this.CssUrl.Url); moduleController.UpdateModuleSetting(this.ModuleId, $"{key}{SettingConstants.TEMPLATEFILES}", this.TemplUrl.Url); @@ -2691,7 +2695,7 @@ private void SaveSettingsByKey(string key) EditorController.AddOrUpdateEditorHostSetting($"{key}{SettingConstants.RESIZEHEIGHT}", this.txtResizeHeight.Text); } - EditorController.AddOrUpdateEditorHostSetting($"{key}injectjs", this.InjectSyntaxJs.Checked.ToString()); + EditorController.AddOrUpdateEditorHostSetting($"{key}{SettingConstants.INJECTJS}", this.InjectSyntaxJs.Checked.ToString()); if (Utility.IsUnit(this.txtWidth.Text)) { @@ -2709,6 +2713,8 @@ private void SaveSettingsByKey(string key) EditorController.AddOrUpdateEditorHostSetting($"{key}{SettingConstants.CUSTOMJSFILE}", this.CustomJsFile.Url); EditorController.AddOrUpdateEditorHostSetting($"{key}{SettingConstants.CONFIG}", this.ConfigUrl.Url); + EditorController.AddOrUpdateEditorHostSetting($"{key}{SettingConstants.BROWSERALLOWFOLLOWFOLDERPERMS}", this.BrowAllowFollowPerms.Checked.ToString()); + var sRoles = this.chblBrowsGr.Items.Cast() .Where(item => item.Selected) .Aggregate(string.Empty, (current, item) => current + (item.Value + ";")); diff --git a/DNN Platform/Providers/HtmlEditorProviders/DNNConnect.CKE/CKEditorOptions.ascx.designer.cs b/DNN Platform/Providers/HtmlEditorProviders/DNNConnect.CKE/CKEditorOptions.ascx.designer.cs index c05ab4d97f2..c04e14d04b2 100644 --- a/DNN Platform/Providers/HtmlEditorProviders/DNNConnect.CKE/CKEditorOptions.ascx.designer.cs +++ b/DNN Platform/Providers/HtmlEditorProviders/DNNConnect.CKE/CKEditorOptions.ascx.designer.cs @@ -14,882 +14,1152 @@ namespace DNNConnect.CKEditorProvider public partial class CKEditorOptions { - /// lblSettings control. + /// + /// lblSettings control. + /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.Label lblSettings; - /// upOptions control. + /// + /// upOptions control. + /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.UpdatePanel upOptions; - /// LastTabId control. + /// + /// LastTabId control. + /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.HiddenField LastTabId; - /// pnlEditor control. + /// + /// pnlEditor control. + /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.Panel pnlEditor; - /// lblSetFor control. + /// + /// lblSetFor control. + /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.Label lblSetFor; - /// rBlSetMode control. + /// + /// rBlSetMode control. + /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.RadioButtonList rBlSetMode; - /// lblMainSet control. + /// + /// lblMainSet control. + /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.Label lblMainSet; - /// lblBrowsSec control. + /// + /// lblBrowsSec control. + /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.Label lblBrowsSec; - /// lblCustomToolbars control. + /// + /// lblCustomToolbars control. + /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.Label lblCustomToolbars; - /// lblEditorConfig control. + /// + /// lblEditorConfig control. + /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.Label lblEditorConfig; - /// InfoTabLi control. + /// + /// InfoTabLi control. + /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.HtmlControls.HtmlGenericControl InfoTabLi; - /// lblHeader control. + /// + /// lblHeader control. + /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.Label lblHeader; - /// lblBlanktext control. + /// + /// lblBlanktext control. + /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.Label lblBlanktext; - /// txtBlanktext control. + /// + /// txtBlanktext control. + /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.TextBox txtBlanktext; - /// lblSkin control. + /// + /// lblSkin control. + /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.Label lblSkin; - /// ddlSkin control. + /// + /// ddlSkin control. + /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.DropDownList ddlSkin; - /// lblWidth control. + /// + /// lblWidth control. + /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.Label lblWidth; - /// txtWidth control. + /// + /// txtWidth control. + /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.TextBox txtWidth; - /// lblHeight control. + /// + /// lblHeight control. + /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.Label lblHeight; - /// txtHeight control. + /// + /// txtHeight control. + /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.TextBox txtHeight; - /// lblToolbars control. + /// + /// lblToolbars control. + /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.Label lblToolbars; - /// gvToolbars control. + /// + /// gvToolbars control. + /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.GridView gvToolbars; - /// lblCustomConfig control. + /// + /// lblCustomConfig control. + /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.Label lblCustomConfig; - /// ctlConfigUrl control. + /// + /// ctlConfigUrl control. + /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::DNNConnect.CKEditorProvider.Controls.UrlControl ctlConfigUrl; - /// CodeMirrorLabel control. + /// + /// CodeMirrorLabel control. + /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.Label CodeMirrorLabel; - /// CodeMirrorTheme control. + /// + /// CodeMirrorTheme control. + /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.DropDownList CodeMirrorTheme; - /// lblInjectSyntaxJs control. + /// + /// lblInjectSyntaxJs control. + /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.Label lblInjectSyntaxJs; - /// InjectSyntaxJs control. + /// + /// InjectSyntaxJs control. + /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.CheckBox InjectSyntaxJs; - /// lblCssurl control. + /// + /// lblCssurl control. + /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.Label lblCssurl; - /// ctlCssurl control. + /// + /// ctlCssurl control. + /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::DNNConnect.CKEditorProvider.Controls.UrlControl ctlCssurl; - /// lblTemplFiles control. + /// + /// lblTemplFiles control. + /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.Label lblTemplFiles; - /// ctlTemplUrl control. + /// + /// ctlTemplUrl control. + /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::DNNConnect.CKEditorProvider.Controls.UrlControl ctlTemplUrl; - /// CustomJsFileLabel control. + /// + /// CustomJsFileLabel control. + /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.Label CustomJsFileLabel; - /// ctlCustomJsFile control. + /// + /// ctlCustomJsFile control. + /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::DNNConnect.CKEditorProvider.Controls.UrlControl ctlCustomJsFile; - /// lblBrowser control. + /// + /// lblBrowser control. + /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.Label lblBrowser; - /// ddlBrowser control. + /// + /// ddlBrowser control. + /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.DropDownList ddlBrowser; - /// lblImageButton control. + /// + /// lblImageButton control. + /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.Label lblImageButton; - /// ddlImageButton control. + /// + /// ddlImageButton control. + /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.DropDownList ddlImageButton; - /// lblBrowAllow control. + /// + /// lblBrowAllowFollowPerms control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.WebControls.Label lblBrowAllowFollowPerms; + + /// + /// BrowAllowFollowPerms control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.WebControls.CheckBox BrowAllowFollowPerms; + + /// + /// lblBrowAllow control. + /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.Label lblBrowAllow; - /// chblBrowsGr control. + /// + /// chblBrowsGr control. + /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.CheckBoxList chblBrowsGr; - /// HostBrowserRootFolder control. + /// + /// HostBrowserRootFolder control. + /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.Label HostBrowserRootFolder; - /// HostBrowserRootDir control. + /// + /// HostBrowserRootDir control. + /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.TextBox HostBrowserRootDir; - /// BrowserRootFolder control. + /// + /// BrowserRootFolder control. + /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.Label BrowserRootFolder; - /// BrowserRootDir control. + /// + /// BrowserRootDir control. + /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.DropDownList BrowserRootDir; - /// HostBrowserRootFolderForImg control. + /// + /// HostBrowserRootFolderForImg control. + /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.Label HostBrowserRootFolderForImg; - /// HostBrowserRootDirForImg control. + /// + /// HostBrowserRootDirForImg control. + /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.TextBox HostBrowserRootDirForImg; - /// BrowserRootFolderForImg control. + /// + /// BrowserRootFolderForImg control. + /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.Label BrowserRootFolderForImg; - /// BrowserRootDirForImg control. + /// + /// BrowserRootDirForImg control. + /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.DropDownList BrowserRootDirForImg; - /// lblBrowserDirs control. + /// + /// lblBrowserDirs control. + /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.Label lblBrowserDirs; - /// cbBrowserDirs control. + /// + /// cbBrowserDirs control. + /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.CheckBox cbBrowserDirs; - /// HostUploadFolderLabel control. + /// + /// HostUploadFolderLabel control. + /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.Label HostUploadFolderLabel; - /// HostUploadDir control. + /// + /// HostUploadDir control. + /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.TextBox HostUploadDir; - /// UploadFolderLabel control. + /// + /// UploadFolderLabel control. + /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.Label UploadFolderLabel; - /// UploadDir control. + /// + /// UploadDir control. + /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.DropDownList UploadDir; - /// HostUploadFolderLabelForImg control. + /// + /// HostUploadFolderLabelForImg control. + /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.Label HostUploadFolderLabelForImg; - /// HostUploadDirForImg control. + /// + /// HostUploadDirForImg control. + /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.TextBox HostUploadDirForImg; - /// UploadDirForImgOption control. + /// + /// UploadDirForImgOption control. + /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.HtmlControls.HtmlGenericControl UploadDirForImgOption; - /// UploadFolderLabelForImg control. + /// + /// UploadFolderLabelForImg control. + /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.Label UploadFolderLabelForImg; - /// UploadDirForImg control. + /// + /// UploadDirForImg control. + /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.DropDownList UploadDirForImg; - /// OverrideFileOnUploadLabel control. + /// + /// OverrideFileOnUploadLabel control. + /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.Label OverrideFileOnUploadLabel; - /// OverrideFileOnUpload control. + /// + /// OverrideFileOnUpload control. + /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.CheckBox OverrideFileOnUpload; - /// UploadFileLimitLabel control. + /// + /// UploadFileLimitLabel control. + /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.Label UploadFileLimitLabel; - /// UploadFileLimits control. + /// + /// UploadFileLimits control. + /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.GridView UploadFileLimits; - /// lblResizeWidthUpload control. + /// + /// lblResizeWidthUpload control. + /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.Label lblResizeWidthUpload; - /// txtResizeWidthUpload control. + /// + /// txtResizeWidthUpload control. + /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.TextBox txtResizeWidthUpload; - /// lblResizeHeightUpload control. + /// + /// lblResizeHeightUpload control. + /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.Label lblResizeHeightUpload; - /// txtResizeHeightUpload control. + /// + /// txtResizeHeightUpload control. + /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.TextBox txtResizeHeightUpload; - /// lblResizeWidth control. + /// + /// lblResizeWidth control. + /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.Label lblResizeWidth; - /// txtResizeWidth control. + /// + /// txtResizeWidth control. + /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.TextBox txtResizeWidth; - /// lblResizeHeight control. + /// + /// lblResizeHeight control. + /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.Label lblResizeHeight; - /// txtResizeHeight control. + /// + /// txtResizeHeight control. + /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.TextBox txtResizeHeight; - /// lblUseAnchorSelector control. + /// + /// lblUseAnchorSelector control. + /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.Label lblUseAnchorSelector; - /// UseAnchorSelector control. + /// + /// UseAnchorSelector control. + /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.CheckBox UseAnchorSelector; - /// lblShowPageLinksTabFirst control. + /// + /// lblShowPageLinksTabFirst control. + /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.Label lblShowPageLinksTabFirst; - /// ShowPageLinksTabFirst control. + /// + /// ShowPageLinksTabFirst control. + /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.CheckBox ShowPageLinksTabFirst; - /// FileListViewModeLabel control. + /// + /// FileListViewModeLabel control. + /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.Label FileListViewModeLabel; - /// FileListViewMode control. + /// + /// FileListViewMode control. + /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.DropDownList FileListViewMode; - /// FileListPageSizeLabel control. + /// + /// FileListPageSizeLabel control. + /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.Label FileListPageSizeLabel; - /// FileListPageSize control. + /// + /// FileListPageSize control. + /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.TextBox FileListPageSize; - /// DefaultLinkModeLabel control. + /// + /// DefaultLinkModeLabel control. + /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.Label DefaultLinkModeLabel; - /// DefaultLinkMode control. + /// + /// DefaultLinkMode control. + /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.DropDownList DefaultLinkMode; - /// lblToolbarList control. + /// + /// lblToolbarList control. + /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.Label lblToolbarList; - /// dDlCustomToolbars control. + /// + /// dDlCustomToolbars control. + /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.DropDownList dDlCustomToolbars; - /// iBEdit control. + /// + /// iBEdit control. + /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.ImageButton iBEdit; - /// iBDelete control. + /// + /// iBDelete control. + /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.ImageButton iBDelete; - /// lblToolbName control. + /// + /// lblToolbName control. + /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.Label lblToolbName; - /// dnnTxtToolBName control. + /// + /// dnnTxtToolBName control. + /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.TextBox dnnTxtToolBName; - /// iBAdd control. + /// + /// iBAdd control. + /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.ImageButton iBAdd; - /// iBCancel control. + /// + /// iBCancel control. + /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.ImageButton iBCancel; - /// lblToolbSet control. + /// + /// lblToolbSet control. + /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.Label lblToolbSet; - /// AvailableToolbarButtons control. + /// + /// AvailableToolbarButtons control. + /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.Repeater AvailableToolbarButtons; - /// ToolbarGroupsLabel control. + /// + /// ToolbarGroupsLabel control. + /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.Label ToolbarGroupsLabel; - /// ToolbarSet control. + /// + /// ToolbarSet control. + /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.HiddenField ToolbarSet; - /// ToolbarGroupsRepeater control. + /// + /// ToolbarGroupsRepeater control. + /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.Repeater ToolbarGroupsRepeater; - /// CreateGroupLabel control. + /// + /// CreateGroupLabel control. + /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.Label CreateGroupLabel; - /// AddRowBreakLabel control. + /// + /// AddRowBreakLabel control. + /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.Label AddRowBreakLabel; - /// lblToolbarPriority control. + /// + /// lblToolbarPriority control. + /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.Label lblToolbarPriority; - /// dDlToolbarPrio control. + /// + /// dDlToolbarPrio control. + /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.DropDownList dDlToolbarPrio; - /// EditorConfigWarning control. + /// + /// EditorConfigWarning control. + /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.Label EditorConfigWarning; - /// EditorConfigHolder control. + /// + /// EditorConfigHolder control. + /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.Panel EditorConfigHolder; - /// InfoTabHolder control. + /// + /// InfoTabHolder control. + /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.PlaceHolder InfoTabHolder; - /// ProviderVersion control. + /// + /// ProviderVersion control. + /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.Label ProviderVersion; - /// lblPortal control. + /// + /// lblPortal control. + /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.Label lblPortal; - /// lblPage control. + /// + /// lblPage control. + /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.Label lblPage; - /// lblModType control. + /// + /// lblModType control. + /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.Label lblModType; - /// lblModName control. + /// + /// lblModName control. + /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.Label lblModName; - /// lblModInst control. + /// + /// lblModInst control. + /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.Label lblModInst; - /// lblUName control. + /// + /// lblUName control. + /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.Label lblUName; - /// btnOk control. + /// + /// btnOk control. + /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.Button btnOk; - /// CopyToAllChild control. + /// + /// CopyToAllChild control. + /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.LinkButton CopyToAllChild; - /// lnkRemoveAll control. + /// + /// lnkRemoveAll control. + /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.LinkButton lnkRemoveAll; - /// lnkRemoveChild control. + /// + /// lnkRemoveChild control. + /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.LinkButton lnkRemoveChild; - /// lnkRemove control. + /// + /// lnkRemove control. + /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.LinkButton lnkRemove; - /// lblImport control. + /// + /// lblImport control. + /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.Label lblImport; - /// lblExport control. + /// + /// lblExport control. + /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.Label lblExport; - /// ExportDialogUpdatePanel control. + /// + /// ExportDialogUpdatePanel control. + /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.UpdatePanel ExportDialogUpdatePanel; - /// ExportDir control. + /// + /// ExportDir control. + /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.DropDownList ExportDir; - /// ExportFileName control. + /// + /// ExportFileName control. + /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.TextBox ExportFileName; - /// ExportNow control. + /// + /// ExportNow control. + /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.LinkButton ExportNow; - /// HiddenMessage control. + /// + /// HiddenMessage control. + /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.HiddenField HiddenMessage; - /// upNewUpdatePanel control. + /// + /// upNewUpdatePanel control. + /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.UpdatePanel upNewUpdatePanel; - /// ctlImportFile control. + /// + /// ctlImportFile control. + /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::DNNConnect.CKEditorProvider.Controls.UrlControl ctlImportFile; - /// lnkImportNow control. + /// + /// lnkImportNow control. + /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.LinkButton lnkImportNow; - /// panelLoading control. + /// + /// panelLoading control. + /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.Panel panelLoading; - /// Wait control. + /// + /// Wait control. + /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.Label Wait; - /// WaitMessage control. + /// + /// WaitMessage control. + /// /// /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. diff --git a/DNN Platform/Providers/HtmlEditorProviders/DNNConnect.CKE/Constants/SettingConstants.cs b/DNN Platform/Providers/HtmlEditorProviders/DNNConnect.CKE/Constants/SettingConstants.cs index 828fa260bfe..9af0706db19 100644 --- a/DNN Platform/Providers/HtmlEditorProviders/DNNConnect.CKE/Constants/SettingConstants.cs +++ b/DNN Platform/Providers/HtmlEditorProviders/DNNConnect.CKE/Constants/SettingConstants.cs @@ -9,7 +9,7 @@ namespace DNNConnect.CKEditorProvider.Constants public static class SettingConstants { /// The Legacy Toolbar Setting XML File Name. - [Obsolete("Legacy XML File")] + [Obsolete("Deprecated in DotNetNuke 7.0.0. Legacy XML file. Scheduled removal in v11.0.0.")] public const string ToolbarXmlFileName = "Dnn.CKToolbar.xml"; /// The Legacy Toolbar Setting XML File Name. @@ -68,6 +68,9 @@ public static class SettingConstants /// The inject JS setting name. public const string INJECTJS = "injectjs"; + + /// The browser allow follow folder permissions setting name. + public const string BROWSERALLOWFOLLOWFOLDERPERMS = "BrowsAllowFolderPerms"; /// The roles setting name. public const string ROLES = "roles"; diff --git a/DNN Platform/Providers/HtmlEditorProviders/DNNConnect.CKE/DNNConnect.CKEditorProvider.csproj b/DNN Platform/Providers/HtmlEditorProviders/DNNConnect.CKE/DNNConnect.CKEditorProvider.csproj index ef5dd3974d6..f64d3da9f3d 100644 --- a/DNN Platform/Providers/HtmlEditorProviders/DNNConnect.CKE/DNNConnect.CKEditorProvider.csproj +++ b/DNN Platform/Providers/HtmlEditorProviders/DNNConnect.CKE/DNNConnect.CKEditorProvider.csproj @@ -44,6 +44,7 @@ + latest true @@ -56,6 +57,8 @@ AllRules.ruleset false none + true + CS0618,SA1600 none @@ -68,6 +71,8 @@ false AllRules.ruleset false + true + CS0618,SA1600 @@ -82,8 +87,7 @@ - ..\..\..\..\packages\Newtonsoft.Json.13.0.2\lib\net45\Newtonsoft.Json.dll - True + ..\..\..\..\packages\Newtonsoft.Json.13.0.3\lib\net45\Newtonsoft.Json.dll @@ -404,6 +408,10 @@ + + {5FE5D021-9C8D-47A6-BD34-F328BA3E709C} + DotNetNuke.Internal.SourceGenerators + {6928A9B1-F88A-4581-A132-D3EB38669BB0} DotNetNuke.Abstractions diff --git a/DNN Platform/Providers/HtmlEditorProviders/DNNConnect.CKE/Objects/EditorProviderSettings.cs b/DNN Platform/Providers/HtmlEditorProviders/DNNConnect.CKE/Objects/EditorProviderSettings.cs index 1c3c79e5727..3ec56b1e1da 100644 --- a/DNN Platform/Providers/HtmlEditorProviders/DNNConnect.CKE/Objects/EditorProviderSettings.cs +++ b/DNN Platform/Providers/HtmlEditorProviders/DNNConnect.CKE/Objects/EditorProviderSettings.cs @@ -30,6 +30,7 @@ public EditorProviderSettings() this.ResizeWidthUpload = -1; this.ResizeHeightUpload = -1; this.ResizeWidth = -1; + this.BrowserAllowFollowFolderPerms = false; this.BrowserRoles = "0;Administrators;"; this.Browser = "standard"; this.ImageButton = "standard"; @@ -166,7 +167,12 @@ public EditorProviderSettings() public ImageButtonType ImageButtonMode { get; set; } /// Gets or sets a value indicating whether which Image Button to use. - public string ImageButton { get; set; } + public string ImageButton { get; set; } + + /// + /// Gets or sets a value indicating whether allowing the file browser will depend on folder permissions. + /// + public bool BrowserAllowFollowFolderPerms { get; set; } /// Gets or sets a value indicating whether Allowed Browser Roles. public string BrowserRoles { get; set; } diff --git a/DNN Platform/Providers/HtmlEditorProviders/DNNConnect.CKE/Objects/SettingBase.cs b/DNN Platform/Providers/HtmlEditorProviders/DNNConnect.CKE/Objects/SettingBase.cs index 319633a0101..1870cca664c 100644 --- a/DNN Platform/Providers/HtmlEditorProviders/DNNConnect.CKE/Objects/SettingBase.cs +++ b/DNN Platform/Providers/HtmlEditorProviders/DNNConnect.CKE/Objects/SettingBase.cs @@ -3,15 +3,15 @@ // See the LICENSE file in the project root for more information namespace DNNConnect.CKEditorProvider.Objects { - using System; using System.Collections.Generic; using System.Web.UI.WebControls; using DNNConnect.CKEditorProvider.Constants; + using DotNetNuke.Internal.SourceGenerators; /// The Settings Base. - [Obsolete("This class is phasing out please use EditorProviderSettings Class instead")] - public class SettingBase : object + [DnnDeprecated(7, 0, 0, "Please use EditorProviderSettings Class instead", RemovalVersion = 11)] + public partial class SettingBase : object { #pragma warning disable SA1300 // Element should begin with upper-case letter /// Gets or sets How many Items to Show per Page on the File List. @@ -92,6 +92,9 @@ public class SettingBase : object /// Gets or sets a value indicating whether Editor File Browser. public string sBrowser { get; set; } + /// Gets or sets a value indicating whether Browser Allow follows Folder Permissions. + public bool BrowserAllowFollowFolderPerms { get; set; } + /// Gets or sets a value indicating whether Allowed Browser Roles. public string sBrowserRoles { get; set; } diff --git a/DNN Platform/Providers/HtmlEditorProviders/DNNConnect.CKE/Objects/Toolbar.cs b/DNN Platform/Providers/HtmlEditorProviders/DNNConnect.CKE/Objects/Toolbar.cs index 7eb8e684b41..19ce35b0e28 100644 --- a/DNN Platform/Providers/HtmlEditorProviders/DNNConnect.CKE/Objects/Toolbar.cs +++ b/DNN Platform/Providers/HtmlEditorProviders/DNNConnect.CKE/Objects/Toolbar.cs @@ -4,11 +4,11 @@ namespace DNNConnect.CKEditorProvider.Objects { - using System; + using DotNetNuke.Internal.SourceGenerators; /// Toolbar Class. - [Obsolete("This class is phasing out please use ToolbarSet Class instead")] - public class Toolbar + [DnnDeprecated(7, 0, 0, "This class is phasing out please use ToolbarSet Class instead", RemovalVersion = 11)] + public partial class Toolbar { #pragma warning disable SA1300 // Element should begin with upper-case letter /// Gets or sets The Name of the Toolbar Set. diff --git a/DNN Platform/Providers/HtmlEditorProviders/DNNConnect.CKE/Utilities/SettingsUtil.cs b/DNN Platform/Providers/HtmlEditorProviders/DNNConnect.CKE/Utilities/SettingsUtil.cs index a129aafbb8f..c88a799c3de 100644 --- a/DNN Platform/Providers/HtmlEditorProviders/DNNConnect.CKE/Utilities/SettingsUtil.cs +++ b/DNN Platform/Providers/HtmlEditorProviders/DNNConnect.CKE/Utilities/SettingsUtil.cs @@ -1,1835 +1,1897 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information - -namespace DNNConnect.CKEditorProvider.Utilities -{ - using System; - using System.Collections; - using System.Collections.Generic; - using System.IO; - using System.Linq; - using System.Reflection; - using System.Web; - using System.Xml; - using System.Xml.Serialization; - - using DNNConnect.CKEditorProvider.Constants; - using DNNConnect.CKEditorProvider.Objects; - using DotNetNuke.Abstractions.Portals; - using DotNetNuke.Common; - using DotNetNuke.Common.Utilities; - using DotNetNuke.Entities.Host; - using DotNetNuke.Entities.Modules; - using DotNetNuke.Entities.Portals; - using DotNetNuke.Security; - using DotNetNuke.Security.Roles; - - /// Settings Base Helper Class. - public class SettingsUtil +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + +namespace DNNConnect.CKEditorProvider.Utilities +{ + using System; + using System.Collections; + using System.Collections.Generic; + using System.IO; + using System.Linq; + using System.Reflection; + using System.Web; + using System.Xml; + using System.Xml.Serialization; + + using DNNConnect.CKEditorProvider.Constants; + using DNNConnect.CKEditorProvider.Objects; + using DotNetNuke.Abstractions.Portals; + using DotNetNuke.Common; + using DotNetNuke.Common.Utilities; + using DotNetNuke.Entities.Host; + using DotNetNuke.Entities.Modules; + using DotNetNuke.Entities.Portals; + using DotNetNuke.Security; + using DotNetNuke.Security.Roles; + + /// Settings Base Helper Class. + public class SettingsUtil { - /// Checks the exists portal or page settings. - /// The editor host settings. - /// The key. - /// - /// Returns if Portal or Page Settings Exists. - /// - internal static bool CheckSettingsExistByKey(List editorHostSettings, string key) - { - if ( - editorHostSettings.Any( - setting => setting.Name.Equals(string.Format("{0}{1}", key, SettingConstants.SKIN)))) - { - return - !string.IsNullOrEmpty( - editorHostSettings.FirstOrDefault( - setting => setting.Name.Equals(string.Format("{0}{1}", key, SettingConstants.SKIN))).Value); - } - - // No Settings Found - return false; + /// Checks the exists portal or page settings. + /// The editor host settings. + /// The key. + /// + /// Returns if Portal or Page Settings Exists. + /// + internal static bool CheckSettingsExistByKey(List editorHostSettings, string key) + { + if ( + editorHostSettings.Any( + setting => setting.Name.Equals(string.Format("{0}{1}", key, SettingConstants.SKIN)))) + { + return + !string.IsNullOrEmpty( + editorHostSettings.FirstOrDefault( + setting => setting.Name.Equals(string.Format("{0}{1}", key, SettingConstants.SKIN))).Value); + } + + // No Settings Found + return false; } - /// Checks there are any Module Settings. - /// The module key. - /// The module id. - /// Returns if The Module Settings Exists or not. - internal static bool CheckExistsModuleSettings(string moduleKey, int moduleId) - { - var module = ModuleController.Instance.GetModule(moduleId, Null.NullInteger, false); - if (module != null) - { - var hshModSet = module.ModuleSettings; - return hshModSet != null && hshModSet.Keys.Cast().Any(key => key.StartsWith(moduleKey)); - } - - return false; + /// Checks there are any Module Settings. + /// The module key. + /// The module id. + /// Returns if The Module Settings Exists or not. + internal static bool CheckExistsModuleSettings(string moduleKey, int moduleId) + { + var module = ModuleController.Instance.GetModule(moduleId, Null.NullInteger, false); + if (module != null) + { + var hshModSet = module.ModuleSettings; + return hshModSet != null && hshModSet.Keys.Cast().Any(key => key.StartsWith(moduleKey)); + } + + return false; } - /// Checks the exists of the module instance settings. - /// The module key. - /// The module id. - /// Returns if The Module Settings Exists or not. - internal static bool CheckExistsModuleInstanceSettings(string moduleKey, int moduleId) - { - var module = ModuleController.Instance.GetModule(moduleId, Null.NullInteger, false); - if (module != null) - { - var hshModSet = module.ModuleSettings; - - return hshModSet != null && !string.IsNullOrEmpty((string)hshModSet[string.Format("{0}skin", moduleKey)]); - } - - return false; + /// Checks the exists of the module instance settings. + /// The module key. + /// The module id. + /// Returns if The Module Settings Exists or not. + internal static bool CheckExistsModuleInstanceSettings(string moduleKey, int moduleId) + { + var module = ModuleController.Instance.GetModule(moduleId, Null.NullInteger, false); + if (module != null) + { + var hshModSet = module.ModuleSettings; + + return hshModSet != null && !string.IsNullOrEmpty((string)hshModSet[string.Format("{0}skin", moduleKey)]); + } + + return false; } - /// Loads the portal or page settings. - /// The current portal settings. - /// The current settings. - /// The editor host settings. - /// The Portal or Page key. - /// The Portal Roles. - /// - /// Returns the Filled Settings. - /// - internal static EditorProviderSettings LoadEditorSettingsByKey( - IPortalSettings portalSettings, - EditorProviderSettings currentSettings, - List editorHostSettings, - string key, - IList portalRoles) - { - var roles = new ArrayList(); - - // Import all Editor config settings - var props = GetEditorConfigProperties().ToList(); - var filteredSettings = editorHostSettings.Where(s => s.Name.StartsWith(key)).ToList(); - - foreach (PropertyInfo info in props) - { - if (!filteredSettings.Any(s => s.Name.Equals(string.Format("{0}{1}", key, info.Name)))) - { - if (!info.Name.Equals("CodeMirror") && !info.Name.Equals("WordCount")) - { - continue; - } - } - - var settingValue = string.Empty; - if (!info.Name.Equals("CodeMirror") && !info.Name.Equals("WordCount")) - { - settingValue = - filteredSettings.FirstOrDefault( - setting => setting.Name.Equals(string.Format("{0}{1}", key, info.Name))).Value; - - if (string.IsNullOrEmpty(settingValue)) - { - continue; - } - - switch (info.PropertyType.Name) - { - case "String": - info.SetValue(currentSettings.Config, settingValue, null); - break; - case "Int32": - info.SetValue(currentSettings.Config, int.Parse(settingValue), null); - break; - case "Decimal": - info.SetValue(currentSettings.Config, decimal.Parse(settingValue), null); - break; - case "Boolean": - info.SetValue(currentSettings.Config, bool.Parse(settingValue), null); - break; - } - } - - switch (info.Name) - { - case "ToolbarLocation": - info.SetValue( - currentSettings.Config, - (ToolBarLocation)Enum.Parse(typeof(ToolBarLocation), settingValue), - null); - break; - case "DefaultLinkType": - info.SetValue( - currentSettings.Config, - (LinkType)Enum.Parse(typeof(LinkType), settingValue), - null); - break; - case "EnterMode": - case "ShiftEnterMode": - info.SetValue( - currentSettings.Config, - (EnterModus)Enum.Parse(typeof(EnterModus), settingValue), - null); - break; - case "ContentsLangDirection": - info.SetValue( - currentSettings.Config, - (LanguageDirection)Enum.Parse(typeof(LanguageDirection), settingValue), - null); - break; - case "CodeMirror": - foreach (var codeMirrorInfo in - typeof(CodeMirror).GetProperties() - .Where(codeMirrorInfo => !codeMirrorInfo.Name.Equals("Theme"))) - { - settingValue = filteredSettings.FirstOrDefault(setting => setting.Name.Equals(string.Format("{0}{1}", key, codeMirrorInfo.Name)))?.Value; - switch (codeMirrorInfo.PropertyType.Name) - { - case "String": - if ( - filteredSettings.Any( - s => s.Name.Equals(string.Format("{0}{1}", key, codeMirrorInfo.Name)))) - { - codeMirrorInfo.SetValue(currentSettings.Config.CodeMirror, settingValue, null); - } - - break; - case "Boolean": - if ( - filteredSettings.Any( - s => s.Name.Equals(string.Format("{0}{1}", key, codeMirrorInfo.Name)))) - { - codeMirrorInfo.SetValue( - currentSettings.Config.CodeMirror, - bool.Parse(settingValue), - null); - } - - break; - } - } - - break; - case "WordCount": - foreach (var wordCountInfo in typeof(WordCountConfig).GetProperties()) - { - settingValue = filteredSettings.FirstOrDefault(setting => setting.Name.Equals(string.Format("{0}{1}", key, wordCountInfo.Name)))?.Value; - switch (wordCountInfo.PropertyType.Name) - { - case "String": - if ( - filteredSettings.Any( - s => s.Name.Equals(string.Format("{0}{1}", key, wordCountInfo.Name)))) - { - wordCountInfo.SetValue(currentSettings.Config.WordCount, settingValue, null); - } - - break; - case "Boolean": - if ( - filteredSettings.Any( - s => s.Name.Equals(string.Format("{0}{1}", key, wordCountInfo.Name)))) - { - wordCountInfo.SetValue( - currentSettings.Config.WordCount, - bool.Parse(settingValue), - null); - } - - break; - } - } - - break; - } - } - - ///////////////// - - if ( - filteredSettings.Any( - setting => setting.Name.Equals(string.Format("{0}{1}", key, SettingConstants.SKIN)))) - { - var settingValue = - filteredSettings.FirstOrDefault( - s => s.Name.Equals(string.Format("{0}{1}", key, SettingConstants.SKIN))).Value; - - if (!string.IsNullOrEmpty(settingValue)) - { - currentSettings.Config.Skin = settingValue; - } - } - - if ( - filteredSettings.Any( - setting => setting.Name.Equals(string.Format("{0}{1}", key, SettingConstants.CODEMIRRORTHEME)))) - { - var settingValue = - filteredSettings.FirstOrDefault( - s => s.Name.Equals(string.Format("{0}{1}", key, SettingConstants.CODEMIRRORTHEME))).Value; - - if (!string.IsNullOrEmpty(settingValue)) - { - currentSettings.Config.CodeMirror.Theme = settingValue; - } - } + /// Loads the portal or page settings. + /// The current portal settings. + /// The current settings. + /// The editor host settings. + /// The Portal or Page key. + /// The Portal Roles. + /// + /// Returns the Filled Settings. + /// + internal static EditorProviderSettings LoadEditorSettingsByKey( + IPortalSettings portalSettings, + EditorProviderSettings currentSettings, + List editorHostSettings, + string key, + IList portalRoles) + { + var roles = new ArrayList(); + + // Import all Editor config settings + var props = GetEditorConfigProperties().ToList(); + var filteredSettings = editorHostSettings.Where(s => s.Name.StartsWith(key)).ToList(); + + foreach (PropertyInfo info in props) + { + if (!filteredSettings.Any(s => s.Name.Equals(string.Format("{0}{1}", key, info.Name)))) + { + if (!info.Name.Equals("CodeMirror") && !info.Name.Equals("WordCount")) + { + continue; + } + } + + var settingValue = string.Empty; + if (!info.Name.Equals("CodeMirror") && !info.Name.Equals("WordCount")) + { + settingValue = + filteredSettings.FirstOrDefault( + setting => setting.Name.Equals(string.Format("{0}{1}", key, info.Name))).Value; + + if (string.IsNullOrEmpty(settingValue)) + { + continue; + } + + switch (info.PropertyType.Name) + { + case "String": + info.SetValue(currentSettings.Config, settingValue, null); + break; + case "Int32": + info.SetValue(currentSettings.Config, int.Parse(settingValue), null); + break; + case "Decimal": + info.SetValue(currentSettings.Config, decimal.Parse(settingValue), null); + break; + case "Boolean": + info.SetValue(currentSettings.Config, bool.Parse(settingValue), null); + break; + } + } + + switch (info.Name) + { + case "ToolbarLocation": + info.SetValue( + currentSettings.Config, + (ToolBarLocation)Enum.Parse(typeof(ToolBarLocation), settingValue), + null); + break; + case "DefaultLinkType": + info.SetValue( + currentSettings.Config, + (LinkType)Enum.Parse(typeof(LinkType), settingValue), + null); + break; + case "EnterMode": + case "ShiftEnterMode": + info.SetValue( + currentSettings.Config, + (EnterModus)Enum.Parse(typeof(EnterModus), settingValue), + null); + break; + case "ContentsLangDirection": + info.SetValue( + currentSettings.Config, + (LanguageDirection)Enum.Parse(typeof(LanguageDirection), settingValue), + null); + break; + case "CodeMirror": + foreach (var codeMirrorInfo in + typeof(CodeMirror).GetProperties() + .Where(codeMirrorInfo => !codeMirrorInfo.Name.Equals("Theme"))) + { + settingValue = filteredSettings.FirstOrDefault(setting => setting.Name.Equals(string.Format("{0}{1}", key, codeMirrorInfo.Name)))?.Value; + switch (codeMirrorInfo.PropertyType.Name) + { + case "String": + if ( + filteredSettings.Any( + s => s.Name.Equals(string.Format("{0}{1}", key, codeMirrorInfo.Name)))) + { + codeMirrorInfo.SetValue(currentSettings.Config.CodeMirror, settingValue, null); + } + + break; + case "Boolean": + if ( + filteredSettings.Any( + s => s.Name.Equals(string.Format("{0}{1}", key, codeMirrorInfo.Name)))) + { + codeMirrorInfo.SetValue( + currentSettings.Config.CodeMirror, + bool.Parse(settingValue), + null); + } + + break; + } + } + + break; + case "WordCount": + foreach (var wordCountInfo in typeof(WordCountConfig).GetProperties()) + { + settingValue = filteredSettings.FirstOrDefault(setting => setting.Name.Equals(string.Format("{0}{1}", key, wordCountInfo.Name)))?.Value; + switch (wordCountInfo.PropertyType.Name) + { + case "String": + if ( + filteredSettings.Any( + s => s.Name.Equals(string.Format("{0}{1}", key, wordCountInfo.Name)))) + { + wordCountInfo.SetValue(currentSettings.Config.WordCount, settingValue, null); + } + + break; + case "Boolean": + if ( + filteredSettings.Any( + s => s.Name.Equals(string.Format("{0}{1}", key, wordCountInfo.Name)))) + { + wordCountInfo.SetValue( + currentSettings.Config.WordCount, + bool.Parse(settingValue), + null); + } + + break; + } + } + + break; + } + } + + ///////////////// + + if ( + filteredSettings.Any( + setting => setting.Name.Equals(string.Format("{0}{1}", key, SettingConstants.SKIN)))) + { + var settingValue = + filteredSettings.FirstOrDefault( + s => s.Name.Equals(string.Format("{0}{1}", key, SettingConstants.SKIN))).Value; + + if (!string.IsNullOrEmpty(settingValue)) + { + currentSettings.Config.Skin = settingValue; + } + } + + if ( + filteredSettings.Any( + setting => setting.Name.Equals(string.Format("{0}{1}", key, SettingConstants.CODEMIRRORTHEME)))) + { + var settingValue = + filteredSettings.FirstOrDefault( + s => s.Name.Equals(string.Format("{0}{1}", key, SettingConstants.CODEMIRRORTHEME))).Value; + + if (!string.IsNullOrEmpty(settingValue)) + { + currentSettings.Config.CodeMirror.Theme = settingValue; + } + } // if we don't have portalRoles, we're in host/allPortals mode - // so we can't filter for the roles, since they're not available - if ((portalRoles?.Count ?? 0) > 0) - { - List listToolbarRoles = (from RoleInfo objRole in portalRoles - where - filteredSettings.Any( - setting => - setting.Name.Equals( - string.Format( - "{0}{2}#{1}", - key, - objRole.RoleID, - SettingConstants.TOOLB))) - where - !string.IsNullOrEmpty( - filteredSettings.FirstOrDefault( - s => - s.Name.Equals( - string.Format( - "{0}{2}#{1}", - key, - objRole.RoleID, - SettingConstants.TOOLB))) - .Value) - let sToolbar = - filteredSettings.FirstOrDefault( - s => - s.Name.Equals( - string.Format( - "{0}{2}#{1}", - key, - objRole.RoleID, - SettingConstants.TOOLB))) - .Value - select - new ToolbarRoles { RoleId = objRole.RoleID, Toolbar = sToolbar }) - .ToList(); - - if ( - filteredSettings.Any( - setting => setting.Name.Equals(string.Format("{0}{2}#{1}", key, "-1", SettingConstants.TOOLB)))) - { - var settingValue = - filteredSettings.FirstOrDefault( - s => s.Name.Equals(string.Format("{0}{2}#{1}", key, "-1", SettingConstants.TOOLB))) - .Value; - - if (!string.IsNullOrEmpty(settingValue)) - { - listToolbarRoles.Add(new ToolbarRoles { RoleId = -1, Toolbar = settingValue }); - } - } - - currentSettings.ToolBarRoles = listToolbarRoles; - - var listUploadSizeRoles = (from RoleInfo objRole in portalRoles - where - filteredSettings.Any( - setting => - setting.Name.Equals( - string.Format( - "{0}{1}#{2}", - key, - objRole.RoleID, - SettingConstants.UPLOADFILELIMITS))) - where - !string.IsNullOrEmpty( - filteredSettings.FirstOrDefault( - s => - s.Name.Equals( - string.Format( - "{0}{1}#{2}", - key, - objRole.RoleID, - SettingConstants.UPLOADFILELIMITS))) - .Value) - let uploadFileLimit = - filteredSettings.FirstOrDefault( - s => - s.Name.Equals( - string.Format( - "{0}{1}#{2}", - key, - objRole.RoleID, - SettingConstants.UPLOADFILELIMITS))) - .Value - select - new UploadSizeRoles - { - RoleId = objRole.RoleID, - RoleName = objRole.RoleName, - UploadFileLimit = Convert.ToInt32(uploadFileLimit) - }) - .ToList(); - - if ( - filteredSettings.Any( - setting => setting.Name.Equals( - string.Format("{0}{1}#{2}", key, "-1", SettingConstants.UPLOADFILELIMITS)))) - { - var settingValue = - filteredSettings.FirstOrDefault( - s => s.Name.Equals( - string.Format("{0}{1}#{2}", key, "-1", SettingConstants.UPLOADFILELIMITS))) - .Value; - - if (!string.IsNullOrEmpty(settingValue)) - { - listUploadSizeRoles.Add( - new UploadSizeRoles { RoleId = -1, UploadFileLimit = Convert.ToInt32(settingValue) }); - } - } - - currentSettings.UploadSizeRoles = listUploadSizeRoles; - - if ( - filteredSettings.Any( - setting => setting.Name.Equals(string.Format("{0}{1}", key, SettingConstants.ROLES)))) - { - var settingValue = - filteredSettings.FirstOrDefault( - s => s.Name.Equals(string.Format("{0}{1}", key, SettingConstants.ROLES))) - .Value; - - if (!string.IsNullOrEmpty(settingValue)) - { - string sRoles = settingValue; - - currentSettings.BrowserRoles = sRoles; - - string[] rolesA = sRoles.Split(';'); - - foreach (string sRoleName in rolesA) - { - if (Utility.IsNumeric(sRoleName)) - { - RoleInfo roleInfo = RoleController.Instance.GetRoleById( - portalSettings.PortalId, - int.Parse(sRoleName)); - - if (roleInfo != null) - { - roles.Add(roleInfo.RoleName); - } - } - else - { - roles.Add(sRoleName); - } - } - } - } - } - - if ( - filteredSettings.Any( - setting => setting.Name.Equals(string.Format("{0}{1}", key, SettingConstants.BROWSER)))) - { - var settingValue = - filteredSettings.FirstOrDefault( - s => s.Name.Equals(string.Format("{0}{1}", key, SettingConstants.BROWSER))).Value; - - if (!string.IsNullOrEmpty(settingValue)) - { - currentSettings.Browser = settingValue; - - switch (currentSettings.Browser) - { - case "ckfinder": - foreach (string sRoleName in roles) - { - if (PortalSecurity.IsInRoles(sRoleName)) - { - currentSettings.BrowserMode = BrowserType.CKFinder; - - break; - } - - currentSettings.BrowserMode = BrowserType.None; - } - - break; - case "standard": - foreach (string sRoleName in roles) - { - if (PortalSecurity.IsInRoles(sRoleName)) - { - currentSettings.BrowserMode = BrowserType.StandardBrowser; - - break; - } - - currentSettings.BrowserMode = BrowserType.None; - } - - break; - case "none": - currentSettings.BrowserMode = BrowserType.None; - break; - } - } - } - - if ( - filteredSettings.Any( - setting => setting.Name.Equals(string.Format("{0}{1}", key, SettingConstants.IMAGEBUTTON)))) - { - var settingValue = - filteredSettings.FirstOrDefault( - s => s.Name.Equals(string.Format("{0}{1}", key, SettingConstants.IMAGEBUTTON))).Value; - - if (!string.IsNullOrEmpty(settingValue)) - { - currentSettings.ImageButton = settingValue; - - if (currentSettings.ImageButton == "easyimage") - { - currentSettings.ImageButtonMode = ImageButtonType.StandardButton; - foreach (string sRoleName in roles) - { - if (PortalSecurity.IsInRoles(sRoleName)) - { - currentSettings.ImageButtonMode = ImageButtonType.EasyImageButton; - } - } - } - else - { - currentSettings.ImageButtonMode = ImageButtonType.StandardButton; + // so we can't filter for the roles, since they're not available + if ((portalRoles?.Count ?? 0) > 0) + { + List listToolbarRoles = (from RoleInfo objRole in portalRoles + where + filteredSettings.Any( + setting => + setting.Name.Equals( + string.Format( + "{0}{2}#{1}", + key, + objRole.RoleID, + SettingConstants.TOOLB))) + where + !string.IsNullOrEmpty( + filteredSettings.FirstOrDefault( + s => + s.Name.Equals( + string.Format( + "{0}{2}#{1}", + key, + objRole.RoleID, + SettingConstants.TOOLB))) + .Value) + let sToolbar = + filteredSettings.FirstOrDefault( + s => + s.Name.Equals( + string.Format( + "{0}{2}#{1}", + key, + objRole.RoleID, + SettingConstants.TOOLB))) + .Value + select + new ToolbarRoles { RoleId = objRole.RoleID, Toolbar = sToolbar }) + .ToList(); + + if ( + filteredSettings.Any( + setting => setting.Name.Equals(string.Format("{0}{2}#{1}", key, "-1", SettingConstants.TOOLB)))) + { + var settingValue = + filteredSettings.FirstOrDefault( + s => s.Name.Equals(string.Format("{0}{2}#{1}", key, "-1", SettingConstants.TOOLB))) + .Value; + + if (!string.IsNullOrEmpty(settingValue)) + { + listToolbarRoles.Add(new ToolbarRoles { RoleId = -1, Toolbar = settingValue }); + } + } + + currentSettings.ToolBarRoles = listToolbarRoles; + + var listUploadSizeRoles = (from RoleInfo objRole in portalRoles + where + filteredSettings.Any( + setting => + setting.Name.Equals( + string.Format( + "{0}{1}#{2}", + key, + objRole.RoleID, + SettingConstants.UPLOADFILELIMITS))) + where + !string.IsNullOrEmpty( + filteredSettings.FirstOrDefault( + s => + s.Name.Equals( + string.Format( + "{0}{1}#{2}", + key, + objRole.RoleID, + SettingConstants.UPLOADFILELIMITS))) + .Value) + let uploadFileLimit = + filteredSettings.FirstOrDefault( + s => + s.Name.Equals( + string.Format( + "{0}{1}#{2}", + key, + objRole.RoleID, + SettingConstants.UPLOADFILELIMITS))) + .Value + select + new UploadSizeRoles + { + RoleId = objRole.RoleID, + RoleName = objRole.RoleName, + UploadFileLimit = Convert.ToInt32(uploadFileLimit), + }) + .ToList(); + + if ( + filteredSettings.Any( + setting => setting.Name.Equals( + string.Format("{0}{1}#{2}", key, "-1", SettingConstants.UPLOADFILELIMITS)))) + { + var settingValue = + filteredSettings.FirstOrDefault( + s => s.Name.Equals( + string.Format("{0}{1}#{2}", key, "-1", SettingConstants.UPLOADFILELIMITS))) + .Value; + + if (!string.IsNullOrEmpty(settingValue)) + { + listUploadSizeRoles.Add( + new UploadSizeRoles { RoleId = -1, UploadFileLimit = Convert.ToInt32(settingValue) }); + } + } + + currentSettings.UploadSizeRoles = listUploadSizeRoles; + + if ( + filteredSettings.Any( + setting => setting.Name.Equals($"{key}{SettingConstants.BROWSERALLOWFOLLOWFOLDERPERMS}"))) + { + var settingValue = + filteredSettings.FirstOrDefault( + s => s.Name.Equals($"{key}{SettingConstants.BROWSERALLOWFOLLOWFOLDERPERMS}")).Value; + + if (!string.IsNullOrEmpty(settingValue)) + { + if (bool.TryParse(settingValue, out var bResult)) + { + currentSettings.BrowserAllowFollowFolderPerms = bResult; + } + } + } + + if ( + filteredSettings.Any( + setting => setting.Name.Equals(string.Format("{0}{1}", key, SettingConstants.ROLES)))) + { + var settingValue = + filteredSettings.FirstOrDefault( + s => s.Name.Equals(string.Format("{0}{1}", key, SettingConstants.ROLES))) + .Value; + + if (!string.IsNullOrEmpty(settingValue)) + { + string sRoles = settingValue; + + currentSettings.BrowserRoles = sRoles; + + string[] rolesA = sRoles.Split(';'); + + foreach (string sRoleName in rolesA) + { + if (Utility.IsNumeric(sRoleName)) + { + RoleInfo roleInfo = RoleController.Instance.GetRoleById( + portalSettings.PortalId, + int.Parse(sRoleName)); + + if (roleInfo != null) + { + roles.Add(roleInfo.RoleName); + } + } + else + { + roles.Add(sRoleName); + } + } + } + } + } + + if ( + filteredSettings.Any( + setting => setting.Name.Equals(string.Format("{0}{1}", key, SettingConstants.BROWSER)))) + { + var settingValue = + filteredSettings.FirstOrDefault( + s => s.Name.Equals(string.Format("{0}{1}", key, SettingConstants.BROWSER))).Value; + + if (!string.IsNullOrEmpty(settingValue)) + { + currentSettings.Browser = settingValue; + + switch (currentSettings.Browser) + { + case "ckfinder": + foreach (string sRoleName in roles) + { + if (PortalSecurity.IsInRoles(sRoleName)) + { + currentSettings.BrowserMode = BrowserType.CKFinder; + + break; + } + + currentSettings.BrowserMode = BrowserType.None; + } + + break; + case "standard": + if (currentSettings.BrowserAllowFollowFolderPerms) + { + if (Utility.CheckIfUserHasFolderReadAccess(currentSettings.BrowserRootDirId, portalSettings)) + { + currentSettings.BrowserMode = BrowserType.StandardBrowser; + break; + } + + currentSettings.BrowserMode = BrowserType.None; + } + + // If the user doesn't get the browser through folder permissions, check the browser-allowed roles + foreach (string sRoleName in roles) + { + if (PortalSecurity.IsInRoles(sRoleName)) + { + currentSettings.BrowserMode = BrowserType.StandardBrowser; + + break; + } + + currentSettings.BrowserMode = BrowserType.None; + } + + break; + case "none": + currentSettings.BrowserMode = BrowserType.None; + break; + } + } + } + + if ( + filteredSettings.Any( + setting => setting.Name.Equals(string.Format("{0}{1}", key, SettingConstants.IMAGEBUTTON)))) + { + var settingValue = + filteredSettings.FirstOrDefault( + s => s.Name.Equals(string.Format("{0}{1}", key, SettingConstants.IMAGEBUTTON))).Value; + + if (!string.IsNullOrEmpty(settingValue)) + { + currentSettings.ImageButton = settingValue; + + if (currentSettings.ImageButton == "easyimage") + { + currentSettings.ImageButtonMode = ImageButtonType.StandardButton; + foreach (string sRoleName in roles) + { + if (PortalSecurity.IsInRoles(sRoleName)) + { + currentSettings.ImageButtonMode = ImageButtonType.EasyImageButton; + } + } + } + else + { + currentSettings.ImageButtonMode = ImageButtonType.StandardButton; + } + } + } + + if ( + filteredSettings.Any( + setting => setting.Name.Equals(string.Format("{0}{1}", key, SettingConstants.INJECTJS)))) + { + var settingValue = + filteredSettings.FirstOrDefault( + s => s.Name.Equals(string.Format("{0}{1}", key, SettingConstants.INJECTJS))).Value; + + if (!string.IsNullOrEmpty(settingValue)) + { + bool bResult; + if (bool.TryParse(settingValue, out bResult)) + { + currentSettings.InjectSyntaxJs = bResult; + } + } + } + + if ( + filteredSettings.Any( + setting => setting.Name.Equals(string.Format("{0}{1}", key, SettingConstants.WIDTH)))) + { + var settingValue = + filteredSettings.FirstOrDefault( + s => s.Name.Equals(string.Format("{0}{1}", key, SettingConstants.WIDTH))).Value; + + if (!string.IsNullOrEmpty(settingValue)) + { + currentSettings.Config.Width = settingValue; + } + } + + if ( + filteredSettings.Any( + setting => setting.Name.Equals(string.Format("{0}{1}", key, SettingConstants.HEIGHT)))) + { + var settingValue = + filteredSettings.FirstOrDefault( + s => s.Name.Equals(string.Format("{0}{1}", key, SettingConstants.HEIGHT))).Value; + + if (!string.IsNullOrEmpty(settingValue)) + { + currentSettings.Config.Height = settingValue; + } + } + + if ( + filteredSettings.Any( + setting => setting.Name.Equals(string.Format("{0}{1}", key, SettingConstants.BLANKTEXT)))) + { + var settingValue = + filteredSettings.FirstOrDefault( + s => s.Name.Equals(string.Format("{0}{1}", key, SettingConstants.BLANKTEXT))).Value; + + if (!string.IsNullOrEmpty(settingValue)) + { + currentSettings.BlankText = settingValue; + } + } + + if ( + filteredSettings.Any( + setting => setting.Name.Equals(string.Format("{0}{1}", key, SettingConstants.CSS)))) + { + var settingValue = + filteredSettings.FirstOrDefault( + s => s.Name.Equals(string.Format("{0}{1}", key, SettingConstants.CSS))).Value; + + if (!string.IsNullOrEmpty(settingValue)) + { + currentSettings.Config.ContentsCss = settingValue; + } + } + + if ( + filteredSettings.Any( + setting => setting.Name.Equals(string.Format("{0}{1}", key, SettingConstants.TEMPLATEFILES)))) + { + var settingValue = + filteredSettings.FirstOrDefault( + s => s.Name.Equals(string.Format("{0}{1}", key, SettingConstants.TEMPLATEFILES))).Value; + + if (!string.IsNullOrEmpty(settingValue)) + { + currentSettings.Config.Templates_Files = settingValue; + } + } + + if ( + filteredSettings.Any( + setting => setting.Name.Equals(string.Format("{0}{1}", key, SettingConstants.CUSTOMJSFILE)))) + { + var settingValue = + filteredSettings.FirstOrDefault( + s => s.Name.Equals(string.Format("{0}{1}", key, SettingConstants.CUSTOMJSFILE))).Value; + + if (!string.IsNullOrEmpty(settingValue)) + { + currentSettings.CustomJsFile = settingValue; + } + } + + if ( + filteredSettings.Any( + setting => setting.Name.Equals(string.Format("{0}{1}", key, SettingConstants.CONFIG)))) + { + var settingValue = + filteredSettings.FirstOrDefault( + s => s.Name.Equals(string.Format("{0}{1}", key, SettingConstants.CONFIG))).Value; + + if (!string.IsNullOrEmpty(settingValue)) + { + currentSettings.Config.CustomConfig = settingValue; + } + } + + if ( + filteredSettings.Any( + setting => setting.Name.Equals(string.Format("{0}{1}", key, SettingConstants.FILELISTPAGESIZE)))) + { + var settingValue = + filteredSettings.FirstOrDefault( + s => s.Name.Equals(string.Format("{0}{1}", key, SettingConstants.FILELISTPAGESIZE))).Value; + + if (!string.IsNullOrEmpty(settingValue)) + { + currentSettings.FileListPageSize = int.Parse(settingValue); + } + } + + if ( + filteredSettings.Any( + setting => setting.Name.Equals(string.Format("{0}{1}", key, SettingConstants.FILELISTVIEWMODE)))) + { + var settingValue = + filteredSettings.FirstOrDefault( + s => s.Name.Equals(string.Format("{0}{1}", key, SettingConstants.FILELISTVIEWMODE))).Value; + + if (!string.IsNullOrEmpty(settingValue)) + { + currentSettings.FileListViewMode = (FileListView)Enum.Parse(typeof(FileListView), settingValue); + } + } + + if ( + filteredSettings.Any( + setting => setting.Name.Equals(string.Format("{0}{1}", key, SettingConstants.DEFAULTLINKMODE)))) + { + var settingValue = + filteredSettings.FirstOrDefault( + s => s.Name.Equals(string.Format("{0}{1}", key, SettingConstants.DEFAULTLINKMODE))).Value; + + if (!string.IsNullOrEmpty(settingValue)) + { + currentSettings.DefaultLinkMode = (LinkMode)Enum.Parse(typeof(LinkMode), settingValue); + } + } + + if ( + filteredSettings.Any( + setting => setting.Name.Equals(string.Format("{0}{1}", key, SettingConstants.USEANCHORSELECTOR)))) + { + var settingValue = + filteredSettings.FirstOrDefault( + s => s.Name.Equals(string.Format("{0}{1}", key, SettingConstants.USEANCHORSELECTOR))).Value; + + if (!string.IsNullOrEmpty(settingValue)) + { + bool bResult; + if (bool.TryParse(settingValue, out bResult)) + { + currentSettings.UseAnchorSelector = bResult; + } + } + } + + if ( + filteredSettings.Any( + setting => setting.Name.Equals(string.Format("{0}{1}", key, SettingConstants.SHOWPAGELINKSTABFIRST)))) + { + var settingValue = + filteredSettings.FirstOrDefault( + s => s.Name.Equals(string.Format("{0}{1}", key, SettingConstants.SHOWPAGELINKSTABFIRST))).Value; + + if (!string.IsNullOrEmpty(settingValue)) + { + bool bResult; + if (bool.TryParse(settingValue, out bResult)) + { + currentSettings.ShowPageLinksTabFirst = bResult; + } + } + } + + if ( + filteredSettings.Any( + setting => setting.Name.Equals(string.Format("{0}{1}", key, SettingConstants.OVERRIDEFILEONUPLOAD)))) + { + var settingValue = + filteredSettings.FirstOrDefault( + s => s.Name.Equals(string.Format("{0}{1}", key, SettingConstants.OVERRIDEFILEONUPLOAD))).Value; + + if (!string.IsNullOrEmpty(settingValue)) + { + bool bResult; + if (bool.TryParse(settingValue, out bResult)) + { + currentSettings.OverrideFileOnUpload = bResult; + } + } + } + + if ( + filteredSettings.Any( + setting => setting.Name.Equals(string.Format("{0}{1}", key, SettingConstants.SUBDIRS)))) + { + var settingValue = + filteredSettings.FirstOrDefault( + s => s.Name.Equals(string.Format("{0}{1}", key, SettingConstants.SUBDIRS))).Value; + + if (!string.IsNullOrEmpty(settingValue)) + { + bool bResult; + if (bool.TryParse(settingValue, out bResult)) + { + currentSettings.SubDirs = bResult; + } + } + } + + if ( + filteredSettings.Any( + setting => setting.Name.Equals(string.Format("{0}{1}", key, SettingConstants.HOSTBROWSERROOTDIR)))) + { + var settingValue = + filteredSettings.FirstOrDefault( + s => s.Name.Equals(string.Format("{0}{1}", key, SettingConstants.HOSTBROWSERROOTDIR))).Value; + + if (!string.IsNullOrEmpty(settingValue)) + { + currentSettings.HostBrowserRootDir = settingValue; + } + } + + if ( + filteredSettings.Any( + setting => setting.Name.Equals(string.Format("{0}{1}", key, SettingConstants.BROWSERROOTDIRID)))) + { + var settingValue = + filteredSettings.FirstOrDefault( + s => s.Name.Equals(string.Format("{0}{1}", key, SettingConstants.BROWSERROOTDIRID))).Value; + + if (!string.IsNullOrEmpty(settingValue)) + { + try + { + currentSettings.BrowserRootDirId = int.Parse(settingValue); + } + catch (Exception) + { + currentSettings.BrowserRootDirId = -1; + } + } + } + + if ( + filteredSettings.Any( + setting => setting.Name.Equals(string.Format("{0}{1}", key, SettingConstants.HOSTBROWSERROOTDIRFORIMG)))) + { + var settingValue = + filteredSettings.FirstOrDefault( + s => s.Name.Equals(string.Format("{0}{1}", key, SettingConstants.HOSTBROWSERROOTDIRFORIMG))).Value; + + if (!string.IsNullOrEmpty(settingValue)) + { + currentSettings.HostBrowserRootDirForImg = settingValue; + } + } + + if ( + filteredSettings.Any( + setting => setting.Name.Equals(string.Format("{0}{1}", key, SettingConstants.BROWSERROOTDIRFORIMGID)))) + { + var settingValue = + filteredSettings.FirstOrDefault( + s => s.Name.Equals(string.Format("{0}{1}", key, SettingConstants.BROWSERROOTDIRFORIMGID))).Value; + + if (!string.IsNullOrEmpty(settingValue)) + { + try + { + currentSettings.BrowserRootDirForImgId = int.Parse(settingValue); + } + catch (Exception) + { + currentSettings.BrowserRootDirForImgId = -1; + } + } + } + + if ( + filteredSettings.Any( + setting => setting.Name.Equals(string.Format("{0}{1}", key, SettingConstants.HOSTUPLOADDIR)))) + { + var settingValue = + filteredSettings.FirstOrDefault( + s => s.Name.Equals(string.Format("{0}{1}", key, SettingConstants.HOSTUPLOADDIR))).Value; + + if (!string.IsNullOrEmpty(settingValue)) + { + currentSettings.HostUploadDir = settingValue; + } + } + + if ( + filteredSettings.Any( + setting => setting.Name.Equals(string.Format("{0}{1}", key, SettingConstants.UPLOADDIRID)))) + { + var settingValue = + filteredSettings.FirstOrDefault( + s => s.Name.Equals(string.Format("{0}{1}", key, SettingConstants.UPLOADDIRID))).Value; + + if (!string.IsNullOrEmpty(settingValue)) + { + try + { + currentSettings.UploadDirId = int.Parse(settingValue); + } + catch (Exception) + { + currentSettings.UploadDirId = -1; + } + } + } + + if ( + filteredSettings.Any( + setting => setting.Name.Equals(string.Format("{0}{1}", key, SettingConstants.HOSTUPLOADDIRFORIMG)))) + { + var settingValue = + filteredSettings.FirstOrDefault( + s => s.Name.Equals(string.Format("{0}{1}", key, SettingConstants.HOSTUPLOADDIRFORIMG))).Value; + + if (!string.IsNullOrEmpty(settingValue)) + { + currentSettings.HostUploadDirForImg = settingValue; + } + } + + if ( + filteredSettings.Any( + setting => setting.Name.Equals(string.Format("{0}{1}", key, SettingConstants.UPLOADDIRFORIMGID)))) + { + var settingValue = + filteredSettings.FirstOrDefault( + s => s.Name.Equals(string.Format("{0}{1}", key, SettingConstants.UPLOADDIRFORIMGID))).Value; + + if (!string.IsNullOrEmpty(settingValue)) + { + try + { + currentSettings.UploadDirForImgId = int.Parse(settingValue); + } + catch (Exception) + { + currentSettings.UploadDirForImgId = -1; + } + } + } + + if ( + filteredSettings.Any( + setting => setting.Name.Equals(string.Format("{0}{1}", key, SettingConstants.RESIZEWIDTHUPLOAD)))) + { + var settingValue = + filteredSettings.FirstOrDefault( + s => s.Name.Equals(string.Format("{0}{1}", key, SettingConstants.RESIZEWIDTHUPLOAD))).Value; + + if (!string.IsNullOrEmpty(settingValue)) + { + try + { + currentSettings.ResizeWidthUpload = int.Parse(settingValue); + } + catch (Exception) + { + currentSettings.ResizeWidthUpload = -1; + } + } + } + + if ( + filteredSettings.Any( + setting => setting.Name.Equals(string.Format("{0}{1}", key, SettingConstants.RESIZEHEIGHTUPLOAD)))) + { + var settingValue = + filteredSettings.FirstOrDefault( + s => s.Name.Equals(string.Format("{0}{1}", key, SettingConstants.RESIZEHEIGHTUPLOAD))).Value; + + if (!string.IsNullOrEmpty(settingValue)) + { + try + { + currentSettings.ResizeHeightUpload = int.Parse(settingValue); + } + catch (Exception) + { + currentSettings.ResizeHeightUpload = -1; + } + } + } + + if ( + filteredSettings.Any( + setting => setting.Name.Equals(string.Format("{0}{1}", key, SettingConstants.RESIZEWIDTH)))) + { + var settingValue = + filteredSettings.FirstOrDefault( + s => s.Name.Equals(string.Format("{0}{1}", key, SettingConstants.RESIZEWIDTH))).Value; + + if (!string.IsNullOrEmpty(settingValue)) + { + try + { + currentSettings.ResizeWidth = int.Parse(settingValue); + } + catch (Exception) + { + currentSettings.ResizeWidth = -1; + } + } + } + + if ( + filteredSettings.Any( + setting => setting.Name.Equals(string.Format("{0}{1}", key, SettingConstants.RESIZEHEIGHT)))) + { + var settingValue = + filteredSettings.FirstOrDefault( + s => s.Name.Equals(string.Format("{0}{1}", key, SettingConstants.RESIZEHEIGHT))).Value; + + if (!string.IsNullOrEmpty(settingValue)) + { + try + { + currentSettings.ResizeHeight = int.Parse(settingValue); + } + catch (Exception) + { + currentSettings.ResizeHeight = -1; + } + } + } + + return currentSettings; + } + + /// Loads the module settings. + /// The portal settings. + /// The current settings. + /// The module key. + /// The module id. + /// The portal roles. + /// + /// Returns the filled Module Settings. + /// + internal static EditorProviderSettings LoadModuleSettings(IPortalSettings portalSettings, EditorProviderSettings currentSettings, string key, int moduleId, IList portalRoles) + { + Hashtable hshModSet = null; + var module = ModuleController.Instance.GetModule(moduleId, Null.NullInteger, false); + if (module != null) + { + hshModSet = module.ModuleSettings; + } + + hshModSet = hshModSet ?? new Hashtable(); + + var roles = new ArrayList(); + + // Import all Editor config settings + foreach ( + PropertyInfo info in + GetEditorConfigProperties() + .Where( + info => + hshModSet != null && !string.IsNullOrEmpty((string)hshModSet[string.Format("{0}{1}", key, info.Name)]))) + { + switch (info.PropertyType.Name) + { + case "String": + info.SetValue(currentSettings.Config, hshModSet[string.Format("{0}{1}", key, info.Name)], null); + break; + case "Int32": + info.SetValue( + currentSettings.Config, + int.Parse((string)hshModSet[string.Format("{0}{1}", key, info.Name)]), + null); + break; + case "Decimal": + info.SetValue( + currentSettings.Config, + decimal.Parse((string)hshModSet[string.Format("{0}{1}", key, info.Name)]), + null); + break; + case "Boolean": + info.SetValue( + currentSettings.Config, + bool.Parse((string)hshModSet[string.Format("{0}{1}", key, info.Name)]), + null); + break; + } + + switch (info.Name) + { + case "ToolbarLocation": + var toolBarLocation = (ToolBarLocation)Enum.Parse( + typeof(ToolBarLocation), + (string)hshModSet[string.Format("{0}{1}", key, info.Name)]); + info.SetValue( + currentSettings.Config, + toolBarLocation, + null); + break; + case "DefaultLinkType": + info.SetValue( + currentSettings.Config, + (LinkType)Enum.Parse(typeof(LinkType), (string)hshModSet[string.Format("{0}{1}", key, info.Name)]), + null); + break; + case "EnterMode": + case "ShiftEnterMode": + info.SetValue( + currentSettings.Config, + (EnterModus)Enum.Parse(typeof(EnterModus), (string)hshModSet[string.Format("{0}{1}", key, info.Name)]), + null); + break; + case "ContentsLangDirection": + var languageDirection = (LanguageDirection)Enum.Parse( + typeof(LanguageDirection), + (string)hshModSet[string.Format("{0}{1}", key, info.Name)]); + info.SetValue( + currentSettings.Config, + languageDirection, + null); + break; + case "CodeMirror": + foreach (var codeMirrorInfo in + typeof(CodeMirror).GetProperties() + .Where(codeMirrorInfo => !codeMirrorInfo.Name.Equals("Theme"))) + { + switch (codeMirrorInfo.PropertyType.Name) + { + case "String": + if (hshModSet.ContainsKey(string.Format("{0}{1}", key, codeMirrorInfo.Name))) + { + codeMirrorInfo.SetValue( + currentSettings.Config.CodeMirror, + hshModSet[string.Format("{0}{1}", key, codeMirrorInfo.Name)], + null); + } + + break; + case "Boolean": + if (hshModSet.ContainsKey(string.Format("{0}{1}", key, codeMirrorInfo.Name))) + { + codeMirrorInfo.SetValue( + currentSettings.Config.CodeMirror, + bool.Parse( + (string)hshModSet[string.Format("{0}{1}", key, codeMirrorInfo.Name)]), + null); + } + + break; + } + } + + break; + case "WordCount": + foreach (var wordCountInfo in typeof(WordCountConfig).GetProperties()) + { + switch (wordCountInfo.PropertyType.Name) + { + case "String": + if (hshModSet.ContainsKey(string.Format("{0}{1}", key, wordCountInfo.Name))) + { + wordCountInfo.SetValue( + currentSettings.Config.WordCount, + hshModSet[string.Format("{0}{1}", key, wordCountInfo.Name)], + null); + } + + break; + case "Boolean": + if (hshModSet.ContainsKey(string.Format("{0}{1}", key, wordCountInfo.Name))) + { + wordCountInfo.SetValue( + currentSettings.Config.WordCount, + bool.Parse( + (string)hshModSet[string.Format("{0}{1}", key, wordCountInfo.Name)]), + null); + } + + break; + } + } + + break; + } + } + + ///////////////// + + if (!string.IsNullOrEmpty((string)hshModSet[string.Format("{0}{1}", key, SettingConstants.SKIN)])) + { + currentSettings.Config.Skin = (string)hshModSet[string.Format("{0}{1}", key, SettingConstants.SKIN)]; + } + + if (!string.IsNullOrEmpty((string)hshModSet[string.Format("{0}{1}", key, SettingConstants.CODEMIRRORTHEME)])) + { + currentSettings.Config.CodeMirror.Theme = (string)hshModSet[string.Format("{0}{1}", key, SettingConstants.CODEMIRRORTHEME)]; + } + + List listToolbarRoles = (from RoleInfo objRole in portalRoles + where + !string.IsNullOrEmpty( + (string)hshModSet[string.Format("{0}{2}#{1}", key, objRole.RoleID, SettingConstants.TOOLB)]) + let sToolbar = + (string)hshModSet[string.Format("{0}{2}#{1}", key, objRole.RoleID, SettingConstants.TOOLB)] + select + new ToolbarRoles { RoleId = objRole.RoleID, Toolbar = sToolbar }) + .ToList(); + + if (!string.IsNullOrEmpty((string)hshModSet[string.Format("{0}{2}#{1}", key, "-1", SettingConstants.TOOLB)])) + { + string sToolbar = (string)hshModSet[string.Format("{0}{2}#{1}", key, "-1", SettingConstants.TOOLB)]; + + listToolbarRoles.Add(new ToolbarRoles { RoleId = -1, Toolbar = sToolbar }); + } + + currentSettings.ToolBarRoles = listToolbarRoles; + + var listUploadSizeRoles = (from RoleInfo objRole in portalRoles + where + !string.IsNullOrEmpty( + (string)hshModSet[string.Format("{0}{1}#{2}", key, objRole.RoleID, SettingConstants.UPLOADFILELIMITS)]) + let uploadFileLimit = + (string)hshModSet[string.Format("{0}{1}#{2}", key, objRole.RoleID, SettingConstants.UPLOADFILELIMITS)] + select + new UploadSizeRoles { RoleId = objRole.RoleID, RoleName = objRole.RoleName, UploadFileLimit = Convert.ToInt32(uploadFileLimit) }) + .ToList(); + + if (!string.IsNullOrEmpty((string)hshModSet[string.Format("{0}{1}#{2}", key, "-1", SettingConstants.UPLOADFILELIMITS)])) + { + listUploadSizeRoles.Add( + new UploadSizeRoles + { + RoleId = -1, + UploadFileLimit = + Convert.ToInt32( + hshModSet[ + string.Format( + "{0}{2}#{1}", + key, + "-1", + SettingConstants.UPLOADFILELIMITS)]), + }); + } + + currentSettings.UploadSizeRoles = listUploadSizeRoles; + + if (!string.IsNullOrEmpty((string)hshModSet[$"{key}{SettingConstants.BROWSERALLOWFOLLOWFOLDERPERMS}"])) + { + bool bResult; + if (bool.TryParse((string)hshModSet[$"{key}{SettingConstants.BROWSERALLOWFOLLOWFOLDERPERMS}"], out bResult)) + { + currentSettings.BrowserAllowFollowFolderPerms = bResult; + } + } + + if (!string.IsNullOrEmpty((string)hshModSet[string.Format("{0}{1}", key, SettingConstants.ROLES)])) + { + string sRoles = (string)hshModSet[string.Format("{0}{1}", key, SettingConstants.ROLES)]; + + currentSettings.BrowserRoles = sRoles; + + string[] rolesA = sRoles.Split(';'); + + foreach (string sRoleName in rolesA) + { + if (Utility.IsNumeric(sRoleName)) + { + RoleInfo roleInfo = RoleController.Instance.GetRoleById(portalSettings.PortalId, int.Parse(sRoleName)); + + if (roleInfo != null) + { + roles.Add(roleInfo.RoleName); + } + } + else + { + roles.Add(sRoleName); + } + } + } + + if (!string.IsNullOrEmpty((string)hshModSet[string.Format("{0}{1}", key, SettingConstants.BROWSER)])) + { + currentSettings.Browser = (string)hshModSet[string.Format("{0}{1}", key, SettingConstants.BROWSER)]; + + switch (currentSettings.Browser) + { + case "ckfinder": + foreach (string sRoleName in roles) + { + if (PortalSecurity.IsInRoles(sRoleName)) + { + currentSettings.BrowserMode = BrowserType.CKFinder; + + break; + } + + currentSettings.BrowserMode = BrowserType.None; + } + + break; + case "standard": + if (currentSettings.BrowserAllowFollowFolderPerms) + { + if (Utility.CheckIfUserHasFolderReadAccess(currentSettings.BrowserRootDirId, portalSettings)) + { + currentSettings.BrowserMode = BrowserType.StandardBrowser; + break; + } + + currentSettings.BrowserMode = BrowserType.None; + } + + // If the user doesn't get the browser through folder permissions, check the browser-allowed roles + foreach (string sRoleName in roles) + { + if (PortalSecurity.IsInRoles(sRoleName)) + { + currentSettings.BrowserMode = BrowserType.StandardBrowser; + + break; + } + + currentSettings.BrowserMode = BrowserType.None; + } + + break; + case "none": + currentSettings.BrowserMode = BrowserType.None; + break; + } + } + + if (!string.IsNullOrEmpty((string)hshModSet[string.Format("{0}{1}", key, SettingConstants.IMAGEBUTTON)])) + { + currentSettings.ImageButton = (string)hshModSet[string.Format("{0}{1}", key, SettingConstants.IMAGEBUTTON)]; + + if (currentSettings.ImageButton == "easyimage") + { + currentSettings.ImageButtonMode = ImageButtonType.StandardButton; + foreach (string sRoleName in roles) + { + if (PortalSecurity.IsInRoles(sRoleName)) + { + currentSettings.ImageButtonMode = ImageButtonType.EasyImageButton; + } + } + } + else + { + currentSettings.ImageButtonMode = ImageButtonType.StandardButton; + } + } + + if (!string.IsNullOrEmpty((string)hshModSet[string.Format("{0}{1}", key, SettingConstants.INJECTJS)])) + { + bool bResult; + if (bool.TryParse((string)hshModSet[string.Format("{0}{1}", key, SettingConstants.INJECTJS)], out bResult)) + { + currentSettings.InjectSyntaxJs = bResult; + } + } + + if (!string.IsNullOrEmpty((string)hshModSet[string.Format("{0}{1}", key, SettingConstants.WIDTH)])) + { + currentSettings.Config.Width = (string)hshModSet[string.Format("{0}{1}", key, SettingConstants.WIDTH)]; + } + + if (!string.IsNullOrEmpty((string)hshModSet[string.Format("{0}{1}", key, SettingConstants.HEIGHT)])) + { + currentSettings.Config.Height = (string)hshModSet[string.Format("{0}{1}", key, SettingConstants.HEIGHT)]; + } + + if (!string.IsNullOrEmpty((string)hshModSet[string.Format("{0}{1}", key, SettingConstants.BLANKTEXT)])) + { + currentSettings.BlankText = (string)hshModSet[string.Format("{0}{1}", key, SettingConstants.BLANKTEXT)]; + } + + if (!string.IsNullOrEmpty((string)hshModSet[string.Format("{0}{1}", key, SettingConstants.CSS)])) + { + currentSettings.Config.ContentsCss = (string)hshModSet[string.Format("{0}{1}", key, SettingConstants.CSS)]; + } + + if (!string.IsNullOrEmpty((string)hshModSet[string.Format("{0}{1}", key, SettingConstants.TEMPLATEFILES)])) + { + currentSettings.Config.Templates_Files = (string)hshModSet[string.Format("{0}{1}", key, SettingConstants.TEMPLATEFILES)]; + } + + if (!string.IsNullOrEmpty((string)hshModSet[string.Format("{0}{1}", key, SettingConstants.CUSTOMJSFILE)])) + { + currentSettings.CustomJsFile = (string)hshModSet[string.Format("{0}{1}", key, SettingConstants.CUSTOMJSFILE)]; + } + + if (!string.IsNullOrEmpty((string)hshModSet[string.Format("{0}{1}", key, SettingConstants.CONFIG)])) + { + currentSettings.Config.CustomConfig = (string)hshModSet[string.Format("{0}{1}", key, SettingConstants.CONFIG)]; + } + + if (!string.IsNullOrEmpty((string)hshModSet[string.Format("{0}{1}", key, SettingConstants.FILELISTPAGESIZE)])) + { + currentSettings.FileListPageSize = int.Parse((string)hshModSet[string.Format("{0}{1}", key, SettingConstants.FILELISTPAGESIZE)]); + } + + if (!string.IsNullOrEmpty((string)hshModSet[string.Format("{0}{1}", key, SettingConstants.FILELISTVIEWMODE)])) + { + currentSettings.FileListViewMode = + (FileListView)Enum.Parse(typeof(FileListView), (string)hshModSet[string.Format("{0}{1}", key, SettingConstants.FILELISTVIEWMODE)]); + } + + if (!string.IsNullOrEmpty((string)hshModSet[string.Format("{0}{1}", key, SettingConstants.DEFAULTLINKMODE)])) + { + currentSettings.DefaultLinkMode = + (LinkMode)Enum.Parse(typeof(LinkMode), (string)hshModSet[string.Format("{0}{1}", key, SettingConstants.DEFAULTLINKMODE)]); + } + + if (!string.IsNullOrEmpty((string)hshModSet[string.Format("{0}{1}", key, SettingConstants.USEANCHORSELECTOR)])) + { + bool bResult; + if (bool.TryParse((string)hshModSet[string.Format("{0}{1}", key, SettingConstants.USEANCHORSELECTOR)], out bResult)) + { + currentSettings.UseAnchorSelector = bResult; + } + } + + if (!string.IsNullOrEmpty((string)hshModSet[string.Format("{0}{1}", key, SettingConstants.SHOWPAGELINKSTABFIRST)])) + { + bool bResult; + if (bool.TryParse((string)hshModSet[string.Format("{0}{1}", key, SettingConstants.SHOWPAGELINKSTABFIRST)], out bResult)) + { + currentSettings.ShowPageLinksTabFirst = bResult; + } + } + + if (!string.IsNullOrEmpty((string)hshModSet[string.Format("{0}{1}", key, SettingConstants.OVERRIDEFILEONUPLOAD)])) + { + bool bResult; + if (bool.TryParse((string)hshModSet[string.Format("{0}{1}", key, SettingConstants.OVERRIDEFILEONUPLOAD)], out bResult)) + { + currentSettings.OverrideFileOnUpload = bResult; + } + } + + if (!string.IsNullOrEmpty((string)hshModSet[string.Format("{0}{1}", key, SettingConstants.SUBDIRS)])) + { + bool bResult; + if (bool.TryParse((string)hshModSet[string.Format("{0}{1}", key, SettingConstants.SUBDIRS)], out bResult)) + { + currentSettings.SubDirs = bResult; + } + } + + if (!string.IsNullOrEmpty((string)hshModSet[string.Format("{0}{1}", key, SettingConstants.BROWSERROOTDIRID)])) + { + try + { + currentSettings.BrowserRootDirId = int.Parse((string)hshModSet[string.Format("{0}{1}", key, SettingConstants.BROWSERROOTDIRID)]); + } + catch (Exception) + { + currentSettings.BrowserRootDirId = -1; + } + } + + if (!string.IsNullOrEmpty((string)hshModSet[string.Format("{0}{1}", key, SettingConstants.BROWSERROOTDIRFORIMGID)])) + { + try + { + currentSettings.BrowserRootDirForImgId = int.Parse((string)hshModSet[string.Format("{0}{1}", key, SettingConstants.BROWSERROOTDIRFORIMGID)]); + } + catch (Exception) + { + currentSettings.BrowserRootDirForImgId = -1; + } + } + + if (!string.IsNullOrEmpty((string)hshModSet[string.Format("{0}{1}", key, SettingConstants.UPLOADDIRID)])) + { + try + { + currentSettings.UploadDirId = int.Parse((string)hshModSet[string.Format("{0}{1}", key, SettingConstants.UPLOADDIRID)]); + } + catch (Exception) + { + currentSettings.UploadDirId = -1; + } + } + + if (!string.IsNullOrEmpty((string)hshModSet[string.Format("{0}{1}", key, SettingConstants.UPLOADDIRFORIMGID)])) + { + try + { + currentSettings.UploadDirForImgId = int.Parse((string)hshModSet[string.Format("{0}{1}", key, SettingConstants.UPLOADDIRFORIMGID)]); + } + catch (Exception) + { + currentSettings.UploadDirForImgId = -1; + } + } + + if (!string.IsNullOrEmpty((string)hshModSet[string.Format("{0}{1}", key, SettingConstants.RESIZEWIDTHUPLOAD)])) + { + try + { + currentSettings.ResizeWidthUpload = int.Parse((string)hshModSet[string.Format("{0}{1}", key, SettingConstants.RESIZEWIDTHUPLOAD)]); + } + catch (Exception) + { + currentSettings.ResizeWidthUpload = -1; + } + } + + if (!string.IsNullOrEmpty((string)hshModSet[string.Format("{0}{1}", key, SettingConstants.RESIZEHEIGHTUPLOAD)])) + { + try + { + currentSettings.ResizeHeightUpload = int.Parse((string)hshModSet[string.Format("{0}{1}", key, SettingConstants.RESIZEHEIGHTUPLOAD)]); + } + catch (Exception) + { + currentSettings.ResizeHeightUpload = -1; + } + } + + if (!string.IsNullOrEmpty((string)hshModSet[string.Format("{0}{1}", key, SettingConstants.RESIZEWIDTH)])) + { + try + { + currentSettings.ResizeWidth = int.Parse((string)hshModSet[string.Format("{0}{1}", key, SettingConstants.RESIZEWIDTH)]); + } + catch (Exception) + { + currentSettings.ResizeWidth = -1; + } + } + + if (!string.IsNullOrEmpty((string)hshModSet[string.Format("{0}{1}", key, SettingConstants.RESIZEHEIGHT)])) + { + try + { + currentSettings.ResizeHeight = int.Parse((string)hshModSet[string.Format("{0}{1}", key, SettingConstants.RESIZEHEIGHT)]); + } + catch (Exception) + { + currentSettings.ResizeHeight = -1; + } + } + + return currentSettings; + } + + /// Gets the default settings. + /// The portal settings. + /// The home folder path. + /// The alternate Sub Folder. + /// The portal roles. + /// + /// Returns the Default Provider Settings. + /// + internal static EditorProviderSettings GetDefaultSettings(IPortalSettings portalSettings, string homeDirPath, string alternateSubFolder, IList portalRoles) + { + var roles = new ArrayList(); + + if (!string.IsNullOrEmpty(alternateSubFolder)) + { + var alternatePath = Path.Combine(homeDirPath, alternateSubFolder); + + if (!Directory.Exists(alternatePath)) + { + Directory.CreateDirectory(alternatePath); + } + + homeDirPath = alternatePath; + } + + // Check if old Settings File Exists + if (File.Exists(Path.Combine(homeDirPath, SettingConstants.XmlDefaultFileName))) + { + // Import Old SettingsBase Xml File + ImportSettingBaseXml(homeDirPath); + } + + if (!File.Exists(Path.Combine(homeDirPath, SettingConstants.XmlSettingsFileName))) + { + if (!File.Exists(Path.Combine(Globals.HostMapPath, SettingConstants.XmlDefaultFileName))) + { + CreateDefaultSettingsFile(); + } + else + { + // Import Old SettingBase Xml File + ImportSettingBaseXml(Globals.HostMapPath, true); + } + + File.Copy(Path.Combine(Globals.HostMapPath, SettingConstants.XmlDefaultFileName), Path.Combine(homeDirPath, SettingConstants.XmlSettingsFileName)); + } + + var serializer = new XmlSerializer(typeof(EditorProviderSettings)); + var reader = + new StreamReader( + new FileStream( + Path.Combine(homeDirPath, SettingConstants.XmlSettingsFileName), FileMode.Open, FileAccess.Read, FileShare.Read)); + + var settings = (EditorProviderSettings)serializer.Deserialize(reader); + + if (!string.IsNullOrEmpty(settings.EditorWidth)) + { + settings.Config.Width = settings.EditorWidth; + } + + if (!string.IsNullOrEmpty(settings.EditorHeight)) + { + settings.Config.Height = settings.EditorHeight; + } + + // Get Browser Roles + if (!string.IsNullOrEmpty(settings.BrowserRoles)) + { + var rolesString = settings.BrowserRoles; + + if (rolesString.Length >= 1 && rolesString.Contains(";")) + { + string[] rolesA = rolesString.Split(';'); + + foreach (string sRoleName in rolesA) + { + if (Utility.IsNumeric(sRoleName)) + { + RoleInfo roleInfo = RoleController.Instance.GetRoleById(portalSettings?.PortalId ?? Host.HostPortalID, int.Parse(sRoleName)); + + if (roleInfo != null) + { + roles.Add(roleInfo.RoleName); + } + } + else + { + roles.Add(sRoleName); + } } - } - } - - if ( - filteredSettings.Any( - setting => setting.Name.Equals(string.Format("{0}{1}", key, SettingConstants.INJECTJS)))) - { - var settingValue = - filteredSettings.FirstOrDefault( - s => s.Name.Equals(string.Format("{0}{1}", key, SettingConstants.INJECTJS))).Value; - - if (!string.IsNullOrEmpty(settingValue)) - { - bool bResult; - if (bool.TryParse(settingValue, out bResult)) - { - currentSettings.InjectSyntaxJs = bResult; - } - } - } - - if ( - filteredSettings.Any( - setting => setting.Name.Equals(string.Format("{0}{1}", key, SettingConstants.WIDTH)))) - { - var settingValue = - filteredSettings.FirstOrDefault( - s => s.Name.Equals(string.Format("{0}{1}", key, SettingConstants.WIDTH))).Value; - - if (!string.IsNullOrEmpty(settingValue)) - { - currentSettings.Config.Width = settingValue; - } - } - - if ( - filteredSettings.Any( - setting => setting.Name.Equals(string.Format("{0}{1}", key, SettingConstants.HEIGHT)))) - { - var settingValue = - filteredSettings.FirstOrDefault( - s => s.Name.Equals(string.Format("{0}{1}", key, SettingConstants.HEIGHT))).Value; - - if (!string.IsNullOrEmpty(settingValue)) - { - currentSettings.Config.Height = settingValue; - } - } - - if ( - filteredSettings.Any( - setting => setting.Name.Equals(string.Format("{0}{1}", key, SettingConstants.BLANKTEXT)))) - { - var settingValue = - filteredSettings.FirstOrDefault( - s => s.Name.Equals(string.Format("{0}{1}", key, SettingConstants.BLANKTEXT))).Value; - - if (!string.IsNullOrEmpty(settingValue)) - { - currentSettings.BlankText = settingValue; - } - } - - if ( - filteredSettings.Any( - setting => setting.Name.Equals(string.Format("{0}{1}", key, SettingConstants.CSS)))) - { - var settingValue = - filteredSettings.FirstOrDefault( - s => s.Name.Equals(string.Format("{0}{1}", key, SettingConstants.CSS))).Value; - - if (!string.IsNullOrEmpty(settingValue)) - { - currentSettings.Config.ContentsCss = settingValue; - } - } - - if ( - filteredSettings.Any( - setting => setting.Name.Equals(string.Format("{0}{1}", key, SettingConstants.TEMPLATEFILES)))) - { - var settingValue = - filteredSettings.FirstOrDefault( - s => s.Name.Equals(string.Format("{0}{1}", key, SettingConstants.TEMPLATEFILES))).Value; - - if (!string.IsNullOrEmpty(settingValue)) - { - currentSettings.Config.Templates_Files = settingValue; - } - } - - if ( - filteredSettings.Any( - setting => setting.Name.Equals(string.Format("{0}{1}", key, SettingConstants.CUSTOMJSFILE)))) - { - var settingValue = - filteredSettings.FirstOrDefault( - s => s.Name.Equals(string.Format("{0}{1}", key, SettingConstants.CUSTOMJSFILE))).Value; - - if (!string.IsNullOrEmpty(settingValue)) - { - currentSettings.CustomJsFile = settingValue; - } - } - - if ( - filteredSettings.Any( - setting => setting.Name.Equals(string.Format("{0}{1}", key, SettingConstants.CONFIG)))) - { - var settingValue = - filteredSettings.FirstOrDefault( - s => s.Name.Equals(string.Format("{0}{1}", key, SettingConstants.CONFIG))).Value; - - if (!string.IsNullOrEmpty(settingValue)) - { - currentSettings.Config.CustomConfig = settingValue; - } - } - - if ( - filteredSettings.Any( - setting => setting.Name.Equals(string.Format("{0}{1}", key, SettingConstants.FILELISTPAGESIZE)))) - { - var settingValue = - filteredSettings.FirstOrDefault( - s => s.Name.Equals(string.Format("{0}{1}", key, SettingConstants.FILELISTPAGESIZE))).Value; - - if (!string.IsNullOrEmpty(settingValue)) - { - currentSettings.FileListPageSize = int.Parse(settingValue); - } - } - - if ( - filteredSettings.Any( - setting => setting.Name.Equals(string.Format("{0}{1}", key, SettingConstants.FILELISTVIEWMODE)))) - { - var settingValue = - filteredSettings.FirstOrDefault( - s => s.Name.Equals(string.Format("{0}{1}", key, SettingConstants.FILELISTVIEWMODE))).Value; - - if (!string.IsNullOrEmpty(settingValue)) - { - currentSettings.FileListViewMode = (FileListView)Enum.Parse(typeof(FileListView), settingValue); - } - } - - if ( - filteredSettings.Any( - setting => setting.Name.Equals(string.Format("{0}{1}", key, SettingConstants.DEFAULTLINKMODE)))) - { - var settingValue = - filteredSettings.FirstOrDefault( - s => s.Name.Equals(string.Format("{0}{1}", key, SettingConstants.DEFAULTLINKMODE))).Value; - - if (!string.IsNullOrEmpty(settingValue)) - { - currentSettings.DefaultLinkMode = (LinkMode)Enum.Parse(typeof(LinkMode), settingValue); - } - } - - if ( - filteredSettings.Any( - setting => setting.Name.Equals(string.Format("{0}{1}", key, SettingConstants.USEANCHORSELECTOR)))) - { - var settingValue = - filteredSettings.FirstOrDefault( - s => s.Name.Equals(string.Format("{0}{1}", key, SettingConstants.USEANCHORSELECTOR))).Value; - - if (!string.IsNullOrEmpty(settingValue)) - { - bool bResult; - if (bool.TryParse(settingValue, out bResult)) - { - currentSettings.UseAnchorSelector = bResult; - } - } - } - - if ( - filteredSettings.Any( - setting => setting.Name.Equals(string.Format("{0}{1}", key, SettingConstants.SHOWPAGELINKSTABFIRST)))) - { - var settingValue = - filteredSettings.FirstOrDefault( - s => s.Name.Equals(string.Format("{0}{1}", key, SettingConstants.SHOWPAGELINKSTABFIRST))).Value; - - if (!string.IsNullOrEmpty(settingValue)) - { - bool bResult; - if (bool.TryParse(settingValue, out bResult)) - { - currentSettings.ShowPageLinksTabFirst = bResult; - } - } - } - - if ( - filteredSettings.Any( - setting => setting.Name.Equals(string.Format("{0}{1}", key, SettingConstants.OVERRIDEFILEONUPLOAD)))) - { - var settingValue = - filteredSettings.FirstOrDefault( - s => s.Name.Equals(string.Format("{0}{1}", key, SettingConstants.OVERRIDEFILEONUPLOAD))).Value; - - if (!string.IsNullOrEmpty(settingValue)) - { - bool bResult; - if (bool.TryParse(settingValue, out bResult)) - { - currentSettings.OverrideFileOnUpload = bResult; - } - } - } - - if ( - filteredSettings.Any( - setting => setting.Name.Equals(string.Format("{0}{1}", key, SettingConstants.SUBDIRS)))) - { - var settingValue = - filteredSettings.FirstOrDefault( - s => s.Name.Equals(string.Format("{0}{1}", key, SettingConstants.SUBDIRS))).Value; - - if (!string.IsNullOrEmpty(settingValue)) - { - bool bResult; - if (bool.TryParse(settingValue, out bResult)) - { - currentSettings.SubDirs = bResult; - } - } - } - - if ( - filteredSettings.Any( - setting => setting.Name.Equals(string.Format("{0}{1}", key, SettingConstants.HOSTBROWSERROOTDIR)))) - { - var settingValue = - filteredSettings.FirstOrDefault( - s => s.Name.Equals(string.Format("{0}{1}", key, SettingConstants.HOSTBROWSERROOTDIR))).Value; - - if (!string.IsNullOrEmpty(settingValue)) - { - currentSettings.HostBrowserRootDir = settingValue; - } - } - - if ( - filteredSettings.Any( - setting => setting.Name.Equals(string.Format("{0}{1}", key, SettingConstants.BROWSERROOTDIRID)))) - { - var settingValue = - filteredSettings.FirstOrDefault( - s => s.Name.Equals(string.Format("{0}{1}", key, SettingConstants.BROWSERROOTDIRID))).Value; - - if (!string.IsNullOrEmpty(settingValue)) - { - try - { - currentSettings.BrowserRootDirId = int.Parse(settingValue); - } - catch (Exception) - { - currentSettings.BrowserRootDirId = -1; - } - } - } - - if ( - filteredSettings.Any( - setting => setting.Name.Equals(string.Format("{0}{1}", key, SettingConstants.HOSTBROWSERROOTDIRFORIMG)))) - { - var settingValue = - filteredSettings.FirstOrDefault( - s => s.Name.Equals(string.Format("{0}{1}", key, SettingConstants.HOSTBROWSERROOTDIRFORIMG))).Value; - - if (!string.IsNullOrEmpty(settingValue)) - { - currentSettings.HostBrowserRootDirForImg = settingValue; - } - } - - if ( - filteredSettings.Any( - setting => setting.Name.Equals(string.Format("{0}{1}", key, SettingConstants.BROWSERROOTDIRFORIMGID)))) - { - var settingValue = - filteredSettings.FirstOrDefault( - s => s.Name.Equals(string.Format("{0}{1}", key, SettingConstants.BROWSERROOTDIRFORIMGID))).Value; - - if (!string.IsNullOrEmpty(settingValue)) - { - try - { - currentSettings.BrowserRootDirForImgId = int.Parse(settingValue); - } - catch (Exception) - { - currentSettings.BrowserRootDirForImgId = -1; - } - } - } - - if ( - filteredSettings.Any( - setting => setting.Name.Equals(string.Format("{0}{1}", key, SettingConstants.HOSTUPLOADDIR)))) - { - var settingValue = - filteredSettings.FirstOrDefault( - s => s.Name.Equals(string.Format("{0}{1}", key, SettingConstants.HOSTUPLOADDIR))).Value; - - if (!string.IsNullOrEmpty(settingValue)) - { - currentSettings.HostUploadDir = settingValue; - } - } - - if ( - filteredSettings.Any( - setting => setting.Name.Equals(string.Format("{0}{1}", key, SettingConstants.UPLOADDIRID)))) - { - var settingValue = - filteredSettings.FirstOrDefault( - s => s.Name.Equals(string.Format("{0}{1}", key, SettingConstants.UPLOADDIRID))).Value; - - if (!string.IsNullOrEmpty(settingValue)) - { - try - { - currentSettings.UploadDirId = int.Parse(settingValue); - } - catch (Exception) - { - currentSettings.UploadDirId = -1; - } - } - } - - if ( - filteredSettings.Any( - setting => setting.Name.Equals(string.Format("{0}{1}", key, SettingConstants.HOSTUPLOADDIRFORIMG)))) - { - var settingValue = - filteredSettings.FirstOrDefault( - s => s.Name.Equals(string.Format("{0}{1}", key, SettingConstants.HOSTUPLOADDIRFORIMG))).Value; - - if (!string.IsNullOrEmpty(settingValue)) - { - currentSettings.HostUploadDirForImg = settingValue; - } - } - - if ( - filteredSettings.Any( - setting => setting.Name.Equals(string.Format("{0}{1}", key, SettingConstants.UPLOADDIRFORIMGID)))) - { - var settingValue = - filteredSettings.FirstOrDefault( - s => s.Name.Equals(string.Format("{0}{1}", key, SettingConstants.UPLOADDIRFORIMGID))).Value; - - if (!string.IsNullOrEmpty(settingValue)) - { - try - { - currentSettings.UploadDirForImgId = int.Parse(settingValue); - } - catch (Exception) - { - currentSettings.UploadDirForImgId = -1; - } - } - } - - if ( - filteredSettings.Any( - setting => setting.Name.Equals(string.Format("{0}{1}", key, SettingConstants.RESIZEWIDTHUPLOAD)))) - { - var settingValue = - filteredSettings.FirstOrDefault( - s => s.Name.Equals(string.Format("{0}{1}", key, SettingConstants.RESIZEWIDTHUPLOAD))).Value; - - if (!string.IsNullOrEmpty(settingValue)) - { - try - { - currentSettings.ResizeWidthUpload = int.Parse(settingValue); - } - catch (Exception) - { - currentSettings.ResizeWidthUpload = -1; - } - } - } - - if ( - filteredSettings.Any( - setting => setting.Name.Equals(string.Format("{0}{1}", key, SettingConstants.RESIZEHEIGHTUPLOAD)))) - { - var settingValue = - filteredSettings.FirstOrDefault( - s => s.Name.Equals(string.Format("{0}{1}", key, SettingConstants.RESIZEHEIGHTUPLOAD))).Value; - - if (!string.IsNullOrEmpty(settingValue)) - { - try - { - currentSettings.ResizeHeightUpload = int.Parse(settingValue); - } - catch (Exception) - { - currentSettings.ResizeHeightUpload = -1; - } - } - } - - if ( - filteredSettings.Any( - setting => setting.Name.Equals(string.Format("{0}{1}", key, SettingConstants.RESIZEWIDTH)))) - { - var settingValue = - filteredSettings.FirstOrDefault( - s => s.Name.Equals(string.Format("{0}{1}", key, SettingConstants.RESIZEWIDTH))).Value; - - if (!string.IsNullOrEmpty(settingValue)) - { - try - { - currentSettings.ResizeWidth = int.Parse(settingValue); - } - catch (Exception) - { - currentSettings.ResizeWidth = -1; - } - } - } - - if ( - filteredSettings.Any( - setting => setting.Name.Equals(string.Format("{0}{1}", key, SettingConstants.RESIZEHEIGHT)))) - { - var settingValue = - filteredSettings.FirstOrDefault( - s => s.Name.Equals(string.Format("{0}{1}", key, SettingConstants.RESIZEHEIGHT))).Value; - - if (!string.IsNullOrEmpty(settingValue)) - { - try - { - currentSettings.ResizeHeight = int.Parse(settingValue); - } - catch (Exception) - { - currentSettings.ResizeHeight = -1; - } - } - } - - return currentSettings; + } + } + + if (!string.IsNullOrEmpty(settings.Browser)) + { + switch (settings.Browser) + { + case "ckfinder": + foreach (string sRoleName in roles) + { + if (PortalSecurity.IsInRoles(sRoleName)) + { + settings.BrowserMode = BrowserType.CKFinder; + + break; + } + + settings.BrowserMode = BrowserType.None; + } + + break; + case "standard": + if (settings.BrowserAllowFollowFolderPerms) + { + if (Utility.CheckIfUserHasFolderReadAccess(settings.BrowserRootDirId, portalSettings)) + { + settings.BrowserMode = BrowserType.StandardBrowser; + break; + } + + settings.BrowserMode = BrowserType.None; + } + + // If the user doesn't get the browser through folder permissions, check the browser-allowed roles + foreach (string sRoleName in roles) + { + if (PortalSecurity.IsInRoles(sRoleName)) + { + settings.BrowserMode = BrowserType.StandardBrowser; + break; + } + + settings.BrowserMode = BrowserType.None; + } + + break; + case "none": + settings.BrowserMode = BrowserType.None; + break; + } + } + + if (!string.IsNullOrEmpty(settings.ImageButton)) + { + if (settings.ImageButton == "easyimage") + { + settings.ImageButtonMode = ImageButtonType.StandardButton; + foreach (string sRoleName in roles) + { + if (PortalSecurity.IsInRoles(sRoleName)) + { + settings.ImageButtonMode = ImageButtonType.EasyImageButton; + } + } + } + else + { + settings.ImageButtonMode = ImageButtonType.StandardButton; + } + } + + reader.Close(); + + return settings; } - /// Loads the module settings. - /// The portal settings. - /// The current settings. - /// The module key. - /// The module id. - /// The portal roles. - /// - /// Returns the filled Module Settings. - /// - internal static EditorProviderSettings LoadModuleSettings(IPortalSettings portalSettings, EditorProviderSettings currentSettings, string key, int moduleId, IList portalRoles) - { - Hashtable hshModSet = null; - var module = ModuleController.Instance.GetModule(moduleId, Null.NullInteger, false); - if (module != null) - { - hshModSet = module.ModuleSettings; - } - - hshModSet = hshModSet ?? new Hashtable(); - - var roles = new ArrayList(); - - // Import all Editor config settings - foreach ( - PropertyInfo info in - GetEditorConfigProperties() - .Where( - info => - hshModSet != null && !string.IsNullOrEmpty((string)hshModSet[string.Format("{0}{1}", key, info.Name)]))) - { - switch (info.PropertyType.Name) - { - case "String": - info.SetValue(currentSettings.Config, hshModSet[string.Format("{0}{1}", key, info.Name)], null); - break; - case "Int32": - info.SetValue( - currentSettings.Config, - int.Parse((string)hshModSet[string.Format("{0}{1}", key, info.Name)]), - null); - break; - case "Decimal": - info.SetValue( - currentSettings.Config, - decimal.Parse((string)hshModSet[string.Format("{0}{1}", key, info.Name)]), - null); - break; - case "Boolean": - info.SetValue( - currentSettings.Config, - bool.Parse((string)hshModSet[string.Format("{0}{1}", key, info.Name)]), - null); - break; - } - - switch (info.Name) - { - case "ToolbarLocation": - var toolBarLocation = (ToolBarLocation)Enum.Parse( - typeof(ToolBarLocation), - (string)hshModSet[string.Format("{0}{1}", key, info.Name)]); - info.SetValue( - currentSettings.Config, - toolBarLocation, - null); - break; - case "DefaultLinkType": - info.SetValue( - currentSettings.Config, - (LinkType)Enum.Parse(typeof(LinkType), (string)hshModSet[string.Format("{0}{1}", key, info.Name)]), - null); - break; - case "EnterMode": - case "ShiftEnterMode": - info.SetValue( - currentSettings.Config, - (EnterModus)Enum.Parse(typeof(EnterModus), (string)hshModSet[string.Format("{0}{1}", key, info.Name)]), - null); - break; - case "ContentsLangDirection": - var languageDirection = (LanguageDirection)Enum.Parse( - typeof(LanguageDirection), - (string)hshModSet[string.Format("{0}{1}", key, info.Name)]); - info.SetValue( - currentSettings.Config, - languageDirection, - null); - break; - case "CodeMirror": - foreach (var codeMirrorInfo in - typeof(CodeMirror).GetProperties() - .Where(codeMirrorInfo => !codeMirrorInfo.Name.Equals("Theme"))) - { - switch (codeMirrorInfo.PropertyType.Name) - { - case "String": - if (hshModSet.ContainsKey(string.Format("{0}{1}", key, codeMirrorInfo.Name))) - { - codeMirrorInfo.SetValue( - currentSettings.Config.CodeMirror, - hshModSet[string.Format("{0}{1}", key, codeMirrorInfo.Name)], - null); - } - - break; - case "Boolean": - if (hshModSet.ContainsKey(string.Format("{0}{1}", key, codeMirrorInfo.Name))) - { - codeMirrorInfo.SetValue( - currentSettings.Config.CodeMirror, - bool.Parse( - (string)hshModSet[string.Format("{0}{1}", key, codeMirrorInfo.Name)]), - null); - } - - break; - } - } - - break; - case "WordCount": - foreach (var wordCountInfo in typeof(WordCountConfig).GetProperties()) - { - switch (wordCountInfo.PropertyType.Name) - { - case "String": - if (hshModSet.ContainsKey(string.Format("{0}{1}", key, wordCountInfo.Name))) - { - wordCountInfo.SetValue( - currentSettings.Config.WordCount, - hshModSet[string.Format("{0}{1}", key, wordCountInfo.Name)], - null); - } - - break; - case "Boolean": - if (hshModSet.ContainsKey(string.Format("{0}{1}", key, wordCountInfo.Name))) - { - wordCountInfo.SetValue( - currentSettings.Config.WordCount, - bool.Parse( - (string)hshModSet[string.Format("{0}{1}", key, wordCountInfo.Name)]), - null); - } - - break; - } - } - - break; - } - } - - ///////////////// - - if (!string.IsNullOrEmpty((string)hshModSet[string.Format("{0}{1}", key, SettingConstants.SKIN)])) - { - currentSettings.Config.Skin = (string)hshModSet[string.Format("{0}{1}", key, SettingConstants.SKIN)]; - } - - if (!string.IsNullOrEmpty((string)hshModSet[string.Format("{0}{1}", key, SettingConstants.CODEMIRRORTHEME)])) - { - currentSettings.Config.CodeMirror.Theme = (string)hshModSet[string.Format("{0}{1}", key, SettingConstants.CODEMIRRORTHEME)]; - } - - List listToolbarRoles = (from RoleInfo objRole in portalRoles - where - !string.IsNullOrEmpty( - (string)hshModSet[string.Format("{0}{2}#{1}", key, objRole.RoleID, SettingConstants.TOOLB)]) - let sToolbar = - (string)hshModSet[string.Format("{0}{2}#{1}", key, objRole.RoleID, SettingConstants.TOOLB)] - select - new ToolbarRoles { RoleId = objRole.RoleID, Toolbar = sToolbar }) - .ToList(); - - if (!string.IsNullOrEmpty((string)hshModSet[string.Format("{0}{2}#{1}", key, "-1", SettingConstants.TOOLB)])) - { - string sToolbar = (string)hshModSet[string.Format("{0}{2}#{1}", key, "-1", SettingConstants.TOOLB)]; - - listToolbarRoles.Add(new ToolbarRoles { RoleId = -1, Toolbar = sToolbar }); - } - - currentSettings.ToolBarRoles = listToolbarRoles; - - var listUploadSizeRoles = (from RoleInfo objRole in portalRoles - where - !string.IsNullOrEmpty( - (string)hshModSet[string.Format("{0}{1}#{2}", key, objRole.RoleID, SettingConstants.UPLOADFILELIMITS)]) - let uploadFileLimit = - (string)hshModSet[string.Format("{0}{1}#{2}", key, objRole.RoleID, SettingConstants.UPLOADFILELIMITS)] - select - new UploadSizeRoles { RoleId = objRole.RoleID, RoleName = objRole.RoleName, UploadFileLimit = Convert.ToInt32(uploadFileLimit) }) - .ToList(); - - if (!string.IsNullOrEmpty((string)hshModSet[string.Format("{0}{1}#{2}", key, "-1", SettingConstants.UPLOADFILELIMITS)])) - { - listUploadSizeRoles.Add( - new UploadSizeRoles - { - RoleId = -1, - UploadFileLimit = - Convert.ToInt32( - hshModSet[ - string.Format( - "{0}{2}#{1}", - key, - "-1", - SettingConstants.UPLOADFILELIMITS)]), - }); - } - - currentSettings.UploadSizeRoles = listUploadSizeRoles; - - if (!string.IsNullOrEmpty((string)hshModSet[string.Format("{0}{1}", key, SettingConstants.ROLES)])) - { - string sRoles = (string)hshModSet[string.Format("{0}{1}", key, SettingConstants.ROLES)]; - - currentSettings.BrowserRoles = sRoles; - - string[] rolesA = sRoles.Split(';'); - - foreach (string sRoleName in rolesA) - { - if (Utility.IsNumeric(sRoleName)) - { - RoleInfo roleInfo = RoleController.Instance.GetRoleById(portalSettings.PortalId, int.Parse(sRoleName)); - - if (roleInfo != null) - { - roles.Add(roleInfo.RoleName); - } - } - else - { - roles.Add(sRoleName); - } - } - } - - if (!string.IsNullOrEmpty((string)hshModSet[string.Format("{0}{1}", key, SettingConstants.BROWSER)])) - { - currentSettings.Browser = (string)hshModSet[string.Format("{0}{1}", key, SettingConstants.BROWSER)]; - - switch (currentSettings.Browser) - { - case "ckfinder": - foreach (string sRoleName in roles) - { - if (PortalSecurity.IsInRoles(sRoleName)) - { - currentSettings.BrowserMode = BrowserType.CKFinder; - - break; - } - - currentSettings.BrowserMode = BrowserType.None; - } - - break; - case "standard": - foreach (string sRoleName in roles) - { - if (PortalSecurity.IsInRoles(sRoleName)) - { - currentSettings.BrowserMode = BrowserType.StandardBrowser; - - break; - } - - currentSettings.BrowserMode = BrowserType.None; - } - - break; - case "none": - currentSettings.BrowserMode = BrowserType.None; - break; - } - } - - if (!string.IsNullOrEmpty((string)hshModSet[string.Format("{0}{1}", key, SettingConstants.IMAGEBUTTON)])) - { - currentSettings.ImageButton = (string)hshModSet[string.Format("{0}{1}", key, SettingConstants.IMAGEBUTTON)]; - - if (currentSettings.ImageButton == "easyimage") - { - currentSettings.ImageButtonMode = ImageButtonType.StandardButton; - foreach (string sRoleName in roles) - { - if (PortalSecurity.IsInRoles(sRoleName)) - { - currentSettings.ImageButtonMode = ImageButtonType.EasyImageButton; - } - } - } - else - { - currentSettings.ImageButtonMode = ImageButtonType.StandardButton; - } - } - - if (!string.IsNullOrEmpty((string)hshModSet[string.Format("{0}{1}", key, SettingConstants.INJECTJS)])) - { - bool bResult; - if (bool.TryParse((string)hshModSet[string.Format("{0}{1}", key, SettingConstants.INJECTJS)], out bResult)) - { - currentSettings.InjectSyntaxJs = bResult; - } - } - - if (!string.IsNullOrEmpty((string)hshModSet[string.Format("{0}{1}", key, SettingConstants.WIDTH)])) - { - currentSettings.Config.Width = (string)hshModSet[string.Format("{0}{1}", key, SettingConstants.WIDTH)]; - } - - if (!string.IsNullOrEmpty((string)hshModSet[string.Format("{0}{1}", key, SettingConstants.HEIGHT)])) - { - currentSettings.Config.Height = (string)hshModSet[string.Format("{0}{1}", key, SettingConstants.HEIGHT)]; - } - - if (!string.IsNullOrEmpty((string)hshModSet[string.Format("{0}{1}", key, SettingConstants.BLANKTEXT)])) - { - currentSettings.BlankText = (string)hshModSet[string.Format("{0}{1}", key, SettingConstants.BLANKTEXT)]; - } - - if (!string.IsNullOrEmpty((string)hshModSet[string.Format("{0}{1}", key, SettingConstants.CSS)])) - { - currentSettings.Config.ContentsCss = (string)hshModSet[string.Format("{0}{1}", key, SettingConstants.CSS)]; - } - - if (!string.IsNullOrEmpty((string)hshModSet[string.Format("{0}{1}", key, SettingConstants.TEMPLATEFILES)])) - { - currentSettings.Config.Templates_Files = (string)hshModSet[string.Format("{0}{1}", key, SettingConstants.TEMPLATEFILES)]; - } - - if (!string.IsNullOrEmpty((string)hshModSet[string.Format("{0}{1}", key, SettingConstants.CUSTOMJSFILE)])) - { - currentSettings.CustomJsFile = (string)hshModSet[string.Format("{0}{1}", key, SettingConstants.CUSTOMJSFILE)]; - } - - if (!string.IsNullOrEmpty((string)hshModSet[string.Format("{0}{1}", key, SettingConstants.CONFIG)])) - { - currentSettings.Config.CustomConfig = (string)hshModSet[string.Format("{0}{1}", key, SettingConstants.CONFIG)]; - } - - if (!string.IsNullOrEmpty((string)hshModSet[string.Format("{0}{1}", key, SettingConstants.FILELISTPAGESIZE)])) - { - currentSettings.FileListPageSize = int.Parse((string)hshModSet[string.Format("{0}{1}", key, SettingConstants.FILELISTPAGESIZE)]); - } - - if (!string.IsNullOrEmpty((string)hshModSet[string.Format("{0}{1}", key, SettingConstants.FILELISTVIEWMODE)])) - { - currentSettings.FileListViewMode = - (FileListView)Enum.Parse(typeof(FileListView), (string)hshModSet[string.Format("{0}{1}", key, SettingConstants.FILELISTVIEWMODE)]); - } - - if (!string.IsNullOrEmpty((string)hshModSet[string.Format("{0}{1}", key, SettingConstants.DEFAULTLINKMODE)])) - { - currentSettings.DefaultLinkMode = - (LinkMode)Enum.Parse(typeof(LinkMode), (string)hshModSet[string.Format("{0}{1}", key, SettingConstants.DEFAULTLINKMODE)]); - } - - if (!string.IsNullOrEmpty((string)hshModSet[string.Format("{0}{1}", key, SettingConstants.USEANCHORSELECTOR)])) - { - bool bResult; - if (bool.TryParse((string)hshModSet[string.Format("{0}{1}", key, SettingConstants.USEANCHORSELECTOR)], out bResult)) - { - currentSettings.UseAnchorSelector = bResult; - } - } - - if (!string.IsNullOrEmpty((string)hshModSet[string.Format("{0}{1}", key, SettingConstants.SHOWPAGELINKSTABFIRST)])) - { - bool bResult; - if (bool.TryParse((string)hshModSet[string.Format("{0}{1}", key, SettingConstants.SHOWPAGELINKSTABFIRST)], out bResult)) - { - currentSettings.ShowPageLinksTabFirst = bResult; - } - } - - if (!string.IsNullOrEmpty((string)hshModSet[string.Format("{0}{1}", key, SettingConstants.OVERRIDEFILEONUPLOAD)])) - { - bool bResult; - if (bool.TryParse((string)hshModSet[string.Format("{0}{1}", key, SettingConstants.OVERRIDEFILEONUPLOAD)], out bResult)) - { - currentSettings.OverrideFileOnUpload = bResult; - } - } - - if (!string.IsNullOrEmpty((string)hshModSet[string.Format("{0}{1}", key, SettingConstants.SUBDIRS)])) - { - bool bResult; - if (bool.TryParse((string)hshModSet[string.Format("{0}{1}", key, SettingConstants.SUBDIRS)], out bResult)) - { - currentSettings.SubDirs = bResult; - } - } - - if (!string.IsNullOrEmpty((string)hshModSet[string.Format("{0}{1}", key, SettingConstants.BROWSERROOTDIRID)])) - { - try - { - currentSettings.BrowserRootDirId = int.Parse((string)hshModSet[string.Format("{0}{1}", key, SettingConstants.BROWSERROOTDIRID)]); - } - catch (Exception) - { - currentSettings.BrowserRootDirId = -1; - } - } - - if (!string.IsNullOrEmpty((string)hshModSet[string.Format("{0}{1}", key, SettingConstants.BROWSERROOTDIRFORIMGID)])) - { - try - { - currentSettings.BrowserRootDirForImgId = int.Parse((string)hshModSet[string.Format("{0}{1}", key, SettingConstants.BROWSERROOTDIRFORIMGID)]); - } - catch (Exception) - { - currentSettings.BrowserRootDirForImgId = -1; - } - } - - if (!string.IsNullOrEmpty((string)hshModSet[string.Format("{0}{1}", key, SettingConstants.UPLOADDIRID)])) - { - try - { - currentSettings.UploadDirId = int.Parse((string)hshModSet[string.Format("{0}{1}", key, SettingConstants.UPLOADDIRID)]); - } - catch (Exception) - { - currentSettings.UploadDirId = -1; - } - } - - if (!string.IsNullOrEmpty((string)hshModSet[string.Format("{0}{1}", key, SettingConstants.UPLOADDIRFORIMGID)])) - { - try - { - currentSettings.UploadDirForImgId = int.Parse((string)hshModSet[string.Format("{0}{1}", key, SettingConstants.UPLOADDIRFORIMGID)]); - } - catch (Exception) - { - currentSettings.UploadDirForImgId = -1; - } - } - - if (!string.IsNullOrEmpty((string)hshModSet[string.Format("{0}{1}", key, SettingConstants.RESIZEWIDTHUPLOAD)])) - { - try - { - currentSettings.ResizeWidthUpload = int.Parse((string)hshModSet[string.Format("{0}{1}", key, SettingConstants.RESIZEWIDTHUPLOAD)]); - } - catch (Exception) - { - currentSettings.ResizeWidthUpload = -1; - } - } - - if (!string.IsNullOrEmpty((string)hshModSet[string.Format("{0}{1}", key, SettingConstants.RESIZEHEIGHTUPLOAD)])) - { - try - { - currentSettings.ResizeHeightUpload = int.Parse((string)hshModSet[string.Format("{0}{1}", key, SettingConstants.RESIZEHEIGHTUPLOAD)]); - } - catch (Exception) - { - currentSettings.ResizeHeightUpload = -1; - } - } - - if (!string.IsNullOrEmpty((string)hshModSet[string.Format("{0}{1}", key, SettingConstants.RESIZEWIDTH)])) - { - try - { - currentSettings.ResizeWidth = int.Parse((string)hshModSet[string.Format("{0}{1}", key, SettingConstants.RESIZEWIDTH)]); - } - catch (Exception) - { - currentSettings.ResizeWidth = -1; - } - } - - if (!string.IsNullOrEmpty((string)hshModSet[string.Format("{0}{1}", key, SettingConstants.RESIZEHEIGHT)])) - { - try - { - currentSettings.ResizeHeight = int.Parse((string)hshModSet[string.Format("{0}{1}", key, SettingConstants.RESIZEHEIGHT)]); - } - catch (Exception) - { - currentSettings.ResizeHeight = -1; - } - } - - return currentSettings; + /// Creates the default settings file. + internal static void CreateDefaultSettingsFile() + { + var newSettings = new EditorProviderSettings(); + + var serializer = new XmlSerializer(typeof(EditorProviderSettings)); + + var textWriter = + new StreamWriter( + new FileStream( + Path.Combine(Globals.HostMapPath, SettingConstants.XmlDefaultFileName), + FileMode.OpenOrCreate, + FileAccess.ReadWrite, + FileShare.ReadWrite)); + + serializer.Serialize(textWriter, newSettings); + + textWriter.Close(); } - /// Gets the default settings. - /// The portal settings. - /// The home folder path. - /// The alternate Sub Folder. - /// The portal roles. - /// - /// Returns the Default Provider Settings. - /// - internal static EditorProviderSettings GetDefaultSettings(IPortalSettings portalSettings, string homeDirPath, string alternateSubFolder, IList portalRoles) - { - var roles = new ArrayList(); - - if (!string.IsNullOrEmpty(alternateSubFolder)) - { - var alternatePath = Path.Combine(homeDirPath, alternateSubFolder); - - if (!Directory.Exists(alternatePath)) - { - Directory.CreateDirectory(alternatePath); - } - - homeDirPath = alternatePath; - } - - // Check if old Settings File Exists - if (File.Exists(Path.Combine(homeDirPath, SettingConstants.XmlDefaultFileName))) - { - // Import Old SettingsBase Xml File - ImportSettingBaseXml(homeDirPath); - } - - if (!File.Exists(Path.Combine(homeDirPath, SettingConstants.XmlSettingsFileName))) - { - if (!File.Exists(Path.Combine(Globals.HostMapPath, SettingConstants.XmlDefaultFileName))) - { - CreateDefaultSettingsFile(); - } - else - { - // Import Old SettingBase Xml File - ImportSettingBaseXml(Globals.HostMapPath, true); - } - - File.Copy(Path.Combine(Globals.HostMapPath, SettingConstants.XmlDefaultFileName), Path.Combine(homeDirPath, SettingConstants.XmlSettingsFileName)); - } - - var serializer = new XmlSerializer(typeof(EditorProviderSettings)); - var reader = - new StreamReader( - new FileStream( - Path.Combine(homeDirPath, SettingConstants.XmlSettingsFileName), FileMode.Open, FileAccess.Read, FileShare.Read)); - - var settings = (EditorProviderSettings)serializer.Deserialize(reader); - - if (!string.IsNullOrEmpty(settings.EditorWidth)) - { - settings.Config.Width = settings.EditorWidth; - } - - if (!string.IsNullOrEmpty(settings.EditorHeight)) - { - settings.Config.Height = settings.EditorHeight; - } - - // Get Browser Roles - if (!string.IsNullOrEmpty(settings.BrowserRoles)) - { - var rolesString = settings.BrowserRoles; - - if (rolesString.Length >= 1 && rolesString.Contains(";")) - { - string[] rolesA = rolesString.Split(';'); - - foreach (string sRoleName in rolesA) - { - if (Utility.IsNumeric(sRoleName)) - { - RoleInfo roleInfo = RoleController.Instance.GetRoleById(portalSettings?.PortalId ?? Host.HostPortalID, int.Parse(sRoleName)); - - if (roleInfo != null) - { - roles.Add(roleInfo.RoleName); - } - } - else - { - roles.Add(sRoleName); - } - } - } - } - - if (!string.IsNullOrEmpty(settings.Browser)) - { - switch (settings.Browser) - { - case "ckfinder": - foreach (string sRoleName in roles) - { - if (PortalSecurity.IsInRoles(sRoleName)) - { - settings.BrowserMode = BrowserType.CKFinder; - - break; - } - - settings.BrowserMode = BrowserType.None; - } - - break; - case "standard": - foreach (string sRoleName in roles) - { - if (PortalSecurity.IsInRoles(sRoleName)) - { - settings.BrowserMode = BrowserType.StandardBrowser; - - break; - } - - settings.BrowserMode = BrowserType.None; - } - - break; - case "none": - settings.BrowserMode = BrowserType.None; - break; - } - } - - if (!string.IsNullOrEmpty(settings.ImageButton)) - { - if (settings.ImageButton == "easyimage") - { - settings.ImageButtonMode = ImageButtonType.StandardButton; - foreach (string sRoleName in roles) - { - if (PortalSecurity.IsInRoles(sRoleName)) - { - settings.ImageButtonMode = ImageButtonType.EasyImageButton; - } - } - } - else - { - settings.ImageButtonMode = ImageButtonType.StandardButton; - } - } - - reader.Close(); - - return settings; - } - - /// Creates the default settings file. - internal static void CreateDefaultSettingsFile() - { - var newSettings = new EditorProviderSettings(); - - var serializer = new XmlSerializer(typeof(EditorProviderSettings)); - - var textWriter = - new StreamWriter( - new FileStream( - Path.Combine(Globals.HostMapPath, SettingConstants.XmlDefaultFileName), - FileMode.OpenOrCreate, - FileAccess.ReadWrite, - FileShare.ReadWrite)); - - serializer.Serialize(textWriter, newSettings); - - textWriter.Close(); - } - - /// Gets the editor config properties. - /// Returns the EditorConfig Properties. - internal static IEnumerable GetEditorConfigProperties() - { - return - typeof(EditorConfig).GetProperties() - .Where( - info => - !info.Name.Equals("Magicline_KeystrokeNext") && !info.Name.Equals("Magicline_KeystrokePrevious") - && !info.Name.Equals("Plugins") && !info.Name.Equals("Codemirror_Theme") - && !info.Name.Equals("Width") && !info.Name.Equals("Height") && !info.Name.Equals("ContentsCss") - && !info.Name.Equals("Templates_Files") && !info.Name.Equals("CustomConfig") - && !info.Name.Equals("Skin") && !info.Name.Equals("Templates_Files") - && !info.Name.Equals("Toolbar") && !info.Name.Equals("Language") - && !info.Name.Equals("FileBrowserWindowWidth") && !info.Name.Equals("FileBrowserWindowHeight") - && !info.Name.Equals("FileBrowserWindowWidth") && !info.Name.Equals("FileBrowserWindowHeight") - && !info.Name.Equals("FileBrowserUploadUrl") && !info.Name.Equals("FileBrowserImageUploadUrl") - && !info.Name.Equals("FilebrowserImageBrowseLinkUrl") - && !info.Name.Equals("FileBrowserImageBrowseUrl") - && !info.Name.Equals("FileBrowserFlashUploadUrl") + /// Gets the editor config properties. + /// Returns the EditorConfig Properties. + internal static IEnumerable GetEditorConfigProperties() + { + return + typeof(EditorConfig).GetProperties() + .Where( + info => + !info.Name.Equals("Magicline_KeystrokeNext") && !info.Name.Equals("Magicline_KeystrokePrevious") + && !info.Name.Equals("Plugins") && !info.Name.Equals("Codemirror_Theme") + && !info.Name.Equals("Width") && !info.Name.Equals("Height") && !info.Name.Equals("ContentsCss") + && !info.Name.Equals("Templates_Files") && !info.Name.Equals("CustomConfig") + && !info.Name.Equals("Skin") && !info.Name.Equals("Templates_Files") + && !info.Name.Equals("Toolbar") && !info.Name.Equals("Language") + && !info.Name.Equals("FileBrowserWindowWidth") && !info.Name.Equals("FileBrowserWindowHeight") + && !info.Name.Equals("FileBrowserWindowWidth") && !info.Name.Equals("FileBrowserWindowHeight") + && !info.Name.Equals("FileBrowserUploadUrl") && !info.Name.Equals("FileBrowserImageUploadUrl") + && !info.Name.Equals("FilebrowserImageBrowseLinkUrl") + && !info.Name.Equals("FileBrowserImageBrowseUrl") + && !info.Name.Equals("FileBrowserFlashUploadUrl") && !info.Name.Equals("FileBrowserFlashBrowseUrl") && !info.Name.Equals("FileBrowserBrowseUrl") - && !info.Name.Equals("DefaultLinkProtocol")); + && !info.Name.Equals("DefaultLinkProtocol")); } - /// Imports the old SettingsBase Xml File. - /// The home folder path. - /// if set to true [is default XML file]. - internal static void ImportSettingBaseXml(string homeDirPath, bool isDefaultXmlFile = false) - { - var oldXmlPath = Path.Combine(homeDirPath, SettingConstants.XmlDefaultFileName); - var oldSerializer = new XmlSerializer(typeof(SettingBase)); - var reader = new XmlTextReader(new FileStream(oldXmlPath, FileMode.Open, FileAccess.Read, FileShare.Read)); - - if (!oldSerializer.CanDeserialize(reader)) - { - reader.Close(); - - return; - } - - var oldDefaultSettings = (SettingBase)oldSerializer.Deserialize(reader); - - reader.Close(); - - // Fix for old skins - if (oldDefaultSettings.sSkin.Equals("office2003") - || oldDefaultSettings.sSkin.Equals("BootstrapCK-Skin") - || oldDefaultSettings.sSkin.Equals("chris") - || oldDefaultSettings.sSkin.Equals("v2")) - { - oldDefaultSettings.sSkin = "moono"; - } - - // Migrate Settings - var importedSettings = new EditorProviderSettings - { - FileListPageSize = oldDefaultSettings.FileListPageSize, - FileListViewMode = oldDefaultSettings.FileListViewMode, - UseAnchorSelector = oldDefaultSettings.UseAnchorSelector, - ShowPageLinksTabFirst = oldDefaultSettings.ShowPageLinksTabFirst, - SubDirs = oldDefaultSettings.bSubDirs, - InjectSyntaxJs = oldDefaultSettings.injectSyntaxJs, - BrowserRootDirId = oldDefaultSettings.BrowserRootDirId, - BrowserRootDirForImgId = oldDefaultSettings.BrowserRootDirForImgId, - UploadDirId = oldDefaultSettings.UploadDirId, - UploadDirForImgId = oldDefaultSettings.UploadDirForImgId, - ResizeHeightUpload = oldDefaultSettings.iResizeHeightUpload, - ResizeWidthUpload = oldDefaultSettings.iResizeWidthUpload, - ResizeHeight = oldDefaultSettings.iResizeHeight, - ResizeWidth = oldDefaultSettings.iResizeWidth, - ToolBarRoles = oldDefaultSettings.listToolbRoles, - BlankText = oldDefaultSettings.sBlankText, - BrowserRoles = oldDefaultSettings.sBrowserRoles, - Browser = oldDefaultSettings.sBrowser, - Config = - { - CustomConfig = oldDefaultSettings.sConfig, - ContentsCss = oldDefaultSettings.sCss, - Skin = oldDefaultSettings.sSkin, - Templates_Files = oldDefaultSettings.sTemplates, - Height = oldDefaultSettings.BrowserHeight, - Width = oldDefaultSettings.BrowserWidth, - AutoParagraph = true, - AutoUpdateElement = true, - BasicEntities = true, - BrowserContextMenuOnCtrl = true, - ColorButton_EnableMore = true, - DisableNativeSpellChecker = true, - DisableNativeTableHandles = true, - EnableTabKeyTools = true, - Entities = true, - Entities_Greek = true, - Entities_Latin = true, - FillEmptyBlocks = true, - IgnoreEmptyParagraph = true, - Image_RemoveLinkByEmptyURL = true, - PasteFromWordRemoveFontStyles = true, - PasteFromWordRemoveStyles = true, - Resize_Enabled = true, - StartupShowBorders = true, - ToolbarGroupCycling = true, - ToolbarStartupExpanded = true, - UseComputedState = true, - AutoGrow_BottomSpace = 0, - AutoGrow_MaxHeight = 0, - AutoGrow_MinHeight = 200, - BaseFloatZIndex = 10000, - Dialog_MagnetDistance = 20, - IndentOffset = 40, - Menu_SubMenuDelay = 400, - Resize_MaxHeight = 600, - Resize_MaxWidth = 3000, - Resize_MinHeight = 250, - Resize_MinWidth = 750, - Scayt_MaxSuggestions = 5, - Smiley_columns = 8, - SourceAreaTabSize = 20, - TabIndex = 0, - TabSpaces = 0, - UndoStackSize = 20, - }, - }; - - // Delete Old File - File.Delete(oldXmlPath); - - // Save new xml file - var newSerializer = new XmlSerializer(typeof(EditorProviderSettings)); - - using ( - var textWriter = - new StreamWriter( - new FileStream( - Path.Combine( - homeDirPath, isDefaultXmlFile ? SettingConstants.XmlDefaultFileName : SettingConstants.XmlSettingsFileName), - FileMode.OpenOrCreate, - FileAccess.ReadWrite, - FileShare.ReadWrite))) - { - newSerializer.Serialize(textWriter, importedSettings); - - textWriter.Close(); - } + /// Imports the old SettingsBase Xml File. + /// The home folder path. + /// if set to true [is default XML file]. + internal static void ImportSettingBaseXml(string homeDirPath, bool isDefaultXmlFile = false) + { + var oldXmlPath = Path.Combine(homeDirPath, SettingConstants.XmlDefaultFileName); + var oldSerializer = new XmlSerializer(typeof(SettingBase)); + var reader = new XmlTextReader(new FileStream(oldXmlPath, FileMode.Open, FileAccess.Read, FileShare.Read)); + + if (!oldSerializer.CanDeserialize(reader)) + { + reader.Close(); + + return; + } + + var oldDefaultSettings = (SettingBase)oldSerializer.Deserialize(reader); + + reader.Close(); + + // Fix for old skins + if (oldDefaultSettings.sSkin.Equals("office2003") + || oldDefaultSettings.sSkin.Equals("BootstrapCK-Skin") + || oldDefaultSettings.sSkin.Equals("chris") + || oldDefaultSettings.sSkin.Equals("v2")) + { + oldDefaultSettings.sSkin = "moono"; + } + + // Migrate Settings + var importedSettings = new EditorProviderSettings + { + FileListPageSize = oldDefaultSettings.FileListPageSize, + FileListViewMode = oldDefaultSettings.FileListViewMode, + UseAnchorSelector = oldDefaultSettings.UseAnchorSelector, + ShowPageLinksTabFirst = oldDefaultSettings.ShowPageLinksTabFirst, + SubDirs = oldDefaultSettings.bSubDirs, + InjectSyntaxJs = oldDefaultSettings.injectSyntaxJs, + BrowserRootDirId = oldDefaultSettings.BrowserRootDirId, + BrowserRootDirForImgId = oldDefaultSettings.BrowserRootDirForImgId, + UploadDirId = oldDefaultSettings.UploadDirId, + UploadDirForImgId = oldDefaultSettings.UploadDirForImgId, + ResizeHeightUpload = oldDefaultSettings.iResizeHeightUpload, + ResizeWidthUpload = oldDefaultSettings.iResizeWidthUpload, + ResizeHeight = oldDefaultSettings.iResizeHeight, + ResizeWidth = oldDefaultSettings.iResizeWidth, + ToolBarRoles = oldDefaultSettings.listToolbRoles, + BlankText = oldDefaultSettings.sBlankText, + BrowserAllowFollowFolderPerms = oldDefaultSettings.BrowserAllowFollowFolderPerms, + BrowserRoles = oldDefaultSettings.sBrowserRoles, + Browser = oldDefaultSettings.sBrowser, + Config = + { + CustomConfig = oldDefaultSettings.sConfig, + ContentsCss = oldDefaultSettings.sCss, + Skin = oldDefaultSettings.sSkin, + Templates_Files = oldDefaultSettings.sTemplates, + Height = oldDefaultSettings.BrowserHeight, + Width = oldDefaultSettings.BrowserWidth, + AutoParagraph = true, + AutoUpdateElement = true, + BasicEntities = true, + BrowserContextMenuOnCtrl = true, + ColorButton_EnableMore = true, + DisableNativeSpellChecker = true, + DisableNativeTableHandles = true, + EnableTabKeyTools = true, + Entities = true, + Entities_Greek = true, + Entities_Latin = true, + FillEmptyBlocks = true, + IgnoreEmptyParagraph = true, + Image_RemoveLinkByEmptyURL = true, + PasteFromWordRemoveFontStyles = true, + PasteFromWordRemoveStyles = true, + Resize_Enabled = true, + StartupShowBorders = true, + ToolbarGroupCycling = true, + ToolbarStartupExpanded = true, + UseComputedState = true, + AutoGrow_BottomSpace = 0, + AutoGrow_MaxHeight = 0, + AutoGrow_MinHeight = 200, + BaseFloatZIndex = 10000, + Dialog_MagnetDistance = 20, + IndentOffset = 40, + Menu_SubMenuDelay = 400, + Resize_MaxHeight = 600, + Resize_MaxWidth = 3000, + Resize_MinHeight = 250, + Resize_MinWidth = 750, + Scayt_MaxSuggestions = 5, + Smiley_columns = 8, + SourceAreaTabSize = 20, + TabIndex = 0, + TabSpaces = 0, + UndoStackSize = 20, + }, + }; + + // Delete Old File + File.Delete(oldXmlPath); + + // Save new xml file + var newSerializer = new XmlSerializer(typeof(EditorProviderSettings)); + + using ( + var textWriter = + new StreamWriter( + new FileStream( + Path.Combine( + homeDirPath, isDefaultXmlFile ? SettingConstants.XmlDefaultFileName : SettingConstants.XmlSettingsFileName), + FileMode.OpenOrCreate, + FileAccess.ReadWrite, + FileShare.ReadWrite))) + { + newSerializer.Serialize(textWriter, importedSettings); + + textWriter.Close(); + } } - /// Gets the size of the current user upload. - /// The settings. - /// The portal settings. - /// The HTTP request. - /// Returns the MAX. upload file size for the current user. - internal static int GetCurrentUserUploadSize(EditorProviderSettings settings, IPortalSettings portalSettings, HttpRequest httpRequest) - { - var uploadFileLimitForPortal = Convert.ToInt32(Utility.GetMaxUploadSize()); - - if (settings.ToolBarRoles.Count <= 0) - { - return uploadFileLimitForPortal; - } - - var listUserUploadFileSizes = new List(); - - foreach (var roleUploadSize in settings.UploadSizeRoles) - { - if (roleUploadSize.RoleId.Equals(-1) && !httpRequest.IsAuthenticated) - { - return roleUploadSize.UploadFileLimit; - } - - if (roleUploadSize.RoleId.Equals(-1)) - { - continue; - } - - // Role - var role = RoleController.Instance.GetRoleById(portalSettings.PortalId, roleUploadSize.RoleId); - - if (role == null) - { - continue; - } - - if (!PortalSecurity.IsInRole(role.RoleName)) - { - continue; - } - - var toolbar = new ToolbarSet(role.RoleName, roleUploadSize.UploadFileLimit); - - listUserUploadFileSizes.Add(toolbar); - } - - if (listUserUploadFileSizes.Count <= 0) - { - return uploadFileLimitForPortal; - } - - // Compare The User Toolbars if the User is more then One Role, and apply the Toolbar with the Highest Priority - int iHighestPrio = listUserUploadFileSizes.Max(toolb => toolb.Priority); - - return listUserUploadFileSizes.Find(toolbarSel => toolbarSel.Priority.Equals(iHighestPrio)).Priority; + /// Gets the size of the current user upload. + /// The settings. + /// The portal settings. + /// The HTTP request. + /// Returns the MAX. upload file size for the current user. + internal static int GetCurrentUserUploadSize(EditorProviderSettings settings, IPortalSettings portalSettings, HttpRequest httpRequest) + { + var uploadFileLimitForPortal = Convert.ToInt32(Utility.GetMaxUploadSize()); + + if (settings.ToolBarRoles.Count <= 0) + { + return uploadFileLimitForPortal; + } + + var listUserUploadFileSizes = new List(); + + foreach (var roleUploadSize in settings.UploadSizeRoles) + { + if (roleUploadSize.RoleId.Equals(-1) && !httpRequest.IsAuthenticated) + { + return roleUploadSize.UploadFileLimit; + } + + if (roleUploadSize.RoleId.Equals(-1)) + { + continue; + } + + // Role + var role = RoleController.Instance.GetRoleById(portalSettings.PortalId, roleUploadSize.RoleId); + + if (role == null) + { + continue; + } + + if (!PortalSecurity.IsInRole(role.RoleName)) + { + continue; + } + + var toolbar = new ToolbarSet(role.RoleName, roleUploadSize.UploadFileLimit); + + listUserUploadFileSizes.Add(toolbar); + } + + if (listUserUploadFileSizes.Count <= 0) + { + return uploadFileLimitForPortal; + } + + // Compare The User Toolbars if the User is more then One Role, and apply the Toolbar with the Highest Priority + int iHighestPrio = listUserUploadFileSizes.Max(toolb => toolb.Priority); + + return listUserUploadFileSizes.Find(toolbarSel => toolbarSel.Priority.Equals(iHighestPrio)).Priority; } - } -} + } +} diff --git a/DNN Platform/Providers/HtmlEditorProviders/DNNConnect.CKE/Utilities/Utility.cs b/DNN Platform/Providers/HtmlEditorProviders/DNNConnect.CKE/Utilities/Utility.cs index 5676ec34723..6385005dc93 100644 --- a/DNN Platform/Providers/HtmlEditorProviders/DNNConnect.CKE/Utilities/Utility.cs +++ b/DNN Platform/Providers/HtmlEditorProviders/DNNConnect.CKE/Utilities/Utility.cs @@ -242,18 +242,18 @@ public static string ConvertUnicodeChars(string input) /// public static bool CheckIfUserHasFolderWriteAccess(int folderId, IPortalSettings portalSettings) { - try - { - var checkFolder = folderId.Equals(-1) - ? ConvertFilePathToFolderInfo(portalSettings.HomeDirectoryMapPath, portalSettings) - : FolderManager.Instance.GetFolder(folderId); + return CheckIfUserHasFolderAccess(folderId, portalSettings, "WRITE"); + } - return FolderPermissionController.HasFolderPermission(checkFolder.FolderPermissions, "WRITE"); - } - catch (Exception) - { - return false; - } + /// Checks if user has read access to the folder. + /// The folder id. + /// The portal settings. + /// + /// Returns if the user has write access to the folder. + /// + public static bool CheckIfUserHasFolderReadAccess(int folderId, IPortalSettings portalSettings) + { + return CheckIfUserHasFolderAccess(folderId, portalSettings, "READ"); } /// Converts a File Path to a Folder Info. @@ -504,5 +504,21 @@ public static IFolderInfo EnsureGetFolder(int portalId, string folderPath) return null; } + + private static bool CheckIfUserHasFolderAccess(int folderId, IPortalSettings portalSettings, string permissionKey) + { + try + { + var checkFolder = folderId.Equals(-1) + ? ConvertFilePathToFolderInfo(portalSettings.HomeDirectoryMapPath, portalSettings) + : FolderManager.Instance.GetFolder(folderId); + + return FolderPermissionController.HasFolderPermission(checkFolder.FolderPermissions, permissionKey); + } + catch (Exception) + { + return false; + } + } } } diff --git a/DNN Platform/Providers/HtmlEditorProviders/DNNConnect.CKE/packages.config b/DNN Platform/Providers/HtmlEditorProviders/DNNConnect.CKE/packages.config index bdc027c685e..803ba4daa3d 100644 --- a/DNN Platform/Providers/HtmlEditorProviders/DNNConnect.CKE/packages.config +++ b/DNN Platform/Providers/HtmlEditorProviders/DNNConnect.CKE/packages.config @@ -4,6 +4,6 @@ - + \ No newline at end of file diff --git a/DNN Platform/Providers/SmtpOAuthProviders/ExchangeOnlineAuthProvider/App_LocalResources/SharedResources.resx b/DNN Platform/Providers/SmtpOAuthProviders/ExchangeOnlineAuthProvider/App_LocalResources/SharedResources.resx new file mode 100644 index 00000000000..0f1ef73b96b --- /dev/null +++ b/DNN Platform/Providers/SmtpOAuthProviders/ExchangeOnlineAuthProvider/App_LocalResources/SharedResources.resx @@ -0,0 +1,141 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + The client id of your app registration. + + + Client Id + + + The client secret of your app registration. + + + Client Secret + + + Exchange Online + + + The teant id of your Microsoft account. + + + Tenant Id + + \ No newline at end of file diff --git a/DNN Platform/Providers/SmtpOAuthProviders/ExchangeOnlineAuthProvider/Authorize.aspx b/DNN Platform/Providers/SmtpOAuthProviders/ExchangeOnlineAuthProvider/Authorize.aspx new file mode 100644 index 00000000000..9e327a4dcae --- /dev/null +++ b/DNN Platform/Providers/SmtpOAuthProviders/ExchangeOnlineAuthProvider/Authorize.aspx @@ -0,0 +1 @@ +<%@ Page Language="C#" AutoEventWireup="false" Inherits="Dnn.ExchangeOnlineAuthProvider.Authorize, Dnn.ExchangeOnlineAuthProvider" CodeBehind="Authorize.aspx.cs" Async="true" %> \ No newline at end of file diff --git a/DNN Platform/Providers/SmtpOAuthProviders/ExchangeOnlineAuthProvider/Authorize.aspx.cs b/DNN Platform/Providers/SmtpOAuthProviders/ExchangeOnlineAuthProvider/Authorize.aspx.cs new file mode 100644 index 00000000000..f3d6ef94e5e --- /dev/null +++ b/DNN Platform/Providers/SmtpOAuthProviders/ExchangeOnlineAuthProvider/Authorize.aspx.cs @@ -0,0 +1,109 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + +namespace Dnn.ExchangeOnlineAuthProvider; + +using System; +using System.Collections.Generic; +using System.Text.RegularExpressions; +using System.Threading; +using System.Threading.Tasks; +using System.Web.UI; + +using Dnn.ExchangeOnlineAuthProvider.Components; +using DotNetNuke.Abstractions.Application; +using DotNetNuke.Common; +using DotNetNuke.Common.Extensions; +using DotNetNuke.Common.Utilities; +using DotNetNuke.Services.Mail.OAuth; +using Microsoft.Extensions.DependencyInjection; + +/// Exchange OAuth callback. +public abstract class Authorize : Page +{ + private readonly ISmtpOAuthController smtpOAuthController; + private readonly IHostSettingsService hostSettingsService; + + /// Initializes a new instance of the class. + protected Authorize() + : this(null, null) + { + } + + /// Initializes a new instance of the class. + /// The SMTP OAuth controller. + /// The host settings service. + protected Authorize(ISmtpOAuthController smtpOAuthController, IHostSettingsService hostSettingsService) + { + if (smtpOAuthController != null) + { + this.smtpOAuthController = smtpOAuthController; + this.hostSettingsService = hostSettingsService; + } + else + { + var serviceProvider = HttpContextSource.Current.GetScope().ServiceProvider; + this.smtpOAuthController = serviceProvider.GetRequiredService(); + this.hostSettingsService = hostSettingsService ?? serviceProvider.GetRequiredService(); + } + } + + /// + /// OnLoad event. + /// + /// Event. + protected override void OnLoad(EventArgs e) + { + base.OnLoad(e); + this.RegisterAsyncTask(new PageAsyncTask(this.OnLoadAsync)); + } + + private async Task OnLoadAsync(CancellationToken cancellationToken) + { + var portalId = Null.NullInteger; + if (this.Request.QueryString["state"] != null) + { + var portalIdStr = RegexUtils.GetCachedRegex("portal_([0-9\\-]+?)_", RegexOptions.IgnoreCase).Match(this.Request.QueryString["state"]).Groups[1].Value; + if (!string.IsNullOrWhiteSpace(portalIdStr)) + { + portalId = Convert.ToInt32(portalIdStr); + } + } + + var authProvider = this.smtpOAuthController.GetOAuthProvider(Constants.Name); + var clientApplication = ExchangeOnlineOAuthProvider.CreateClientApplication(this.smtpOAuthController, this.hostSettingsService, portalId); + + if (clientApplication == null || await authProvider.IsAuthorizedAsync(portalId, cancellationToken)) + { + this.CloseWindow(); + return; + } + + var scopes = ExchangeOnlineOAuthProvider.GetAuthenticationScopes(); + + var code = this.Request["code"]; + if (code != null) + { + _ = await clientApplication.AcquireTokenByAuthorizationCode(scopes, code).ExecuteAsync(cancellationToken); + } + else + { + var queryStrings = new Dictionary + { + { "state", this.Request.QueryString["state"] }, + }; + var msUri = await clientApplication.GetAuthorizationRequestUrl(scopes) + .WithExtraQueryParameters(queryStrings) + .ExecuteAsync(cancellationToken); + this.Response.Redirect(msUri.ToString(), true); + } + + this.CloseWindow(); + } + + private void CloseWindow() + { + this.Response.Write(""); + } +} diff --git a/DNN Platform/Providers/SmtpOAuthProviders/ExchangeOnlineAuthProvider/Components/Constants.cs b/DNN Platform/Providers/SmtpOAuthProviders/ExchangeOnlineAuthProvider/Components/Constants.cs new file mode 100644 index 00000000000..a8ca48883d5 --- /dev/null +++ b/DNN Platform/Providers/SmtpOAuthProviders/ExchangeOnlineAuthProvider/Components/Constants.cs @@ -0,0 +1,33 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + +namespace Dnn.ExchangeOnlineAuthProvider.Components; + +/// Azure connector constants. +internal static class Constants +{ + /// The provider name. + public const string Name = "ExchangeOnline"; + + /// The tenant id setting name. + public const string TenantIdSettingName = "msauth_tenantId"; + + /// The client id setting name. + public const string ClientIdSettingName = "msauth_clientId"; + + /// The client secret setting name. + public const string ClientSecretSettingName = "msauth_clientSecret"; + + /// The access token setting name. + public const string AuthenticationSettingName = "msauth_authentication"; + + /// The authorize callback url. + public const string CallbackUrl = "{0}/Providers/SmtpOAuthProviders/ExchangeOnline/Authorize.aspx?state=portal_{1}_"; + + /// The local resources file path. + public const string LocalResourcesFile = "~/Providers/SmtpOAuthProviders/ExchangeOnline/App_LocalResources/SharedResources.resx"; + + /// The default azure instance. + public const string AzureInstance = "https://login.microsoftonline.com/"; +} diff --git a/DNN Platform/Providers/SmtpOAuthProviders/ExchangeOnlineAuthProvider/Components/ExchangeOnlineOAuthProvider.cs b/DNN Platform/Providers/SmtpOAuthProviders/ExchangeOnlineAuthProvider/Components/ExchangeOnlineOAuthProvider.cs new file mode 100644 index 00000000000..83a2e3478e4 --- /dev/null +++ b/DNN Platform/Providers/SmtpOAuthProviders/ExchangeOnlineAuthProvider/Components/ExchangeOnlineOAuthProvider.cs @@ -0,0 +1,397 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + +namespace Dnn.ExchangeOnlineAuthProvider.Components; + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; + +using DotNetNuke.Abstractions.Application; +using DotNetNuke.Abstractions.Portals; +using DotNetNuke.Collections; +using DotNetNuke.Common.Utilities; +using DotNetNuke.Entities.Host; +using DotNetNuke.Entities.Portals; +using DotNetNuke.Security; +using DotNetNuke.Services.Localization; +using DotNetNuke.Services.Mail.OAuth; + +using Microsoft.Identity.Client; + +/// +public class ExchangeOnlineOAuthProvider : ISmtpOAuthProvider +{ + private readonly IHostSettingsService hostSettingsService; + private readonly IPortalAliasService portalAliasService; + + /// Initializes a new instance of the class. + /// The host settings service. + /// The portal alias service. + public ExchangeOnlineOAuthProvider(IHostSettingsService hostSettingsService, IPortalAliasService portalAliasService) + { + this.hostSettingsService = hostSettingsService; + this.portalAliasService = portalAliasService; + } + + /// + public string Name => Constants.Name; + + /// + public string LocalizedName => Localization.GetSafeJSString(this.Name, Constants.LocalResourcesFile); + + /// + public bool IsAuthorized(int portalId) + { + var clientApplication = CreateClientApplication(this, this.hostSettingsService, portalId); + if (clientApplication == null) + { + return false; + } + + var accounts = clientApplication.GetAccountsAsync().Result; + + return accounts?.Any() ?? false; + } + + /// + public async Task IsAuthorizedAsync(int portalId, CancellationToken cancellationToken = default) + { + var clientApplication = CreateClientApplication(this, this.hostSettingsService, portalId); + if (clientApplication == null) + { + return false; + } + + var accounts = await clientApplication.GetAccountsAsync(cancellationToken); + return accounts?.Any() ?? false; + } + + /// + public string GetAuthorizeUrl(int portalId) + { + var clientId = this.GetSetting(portalId, Constants.ClientIdSettingName); + var clientSecret = this.GetSetting(portalId, Constants.ClientSecretSettingName); + + if (string.IsNullOrWhiteSpace(clientId) + || string.IsNullOrWhiteSpace(clientSecret)) + { + return string.Empty; + } + + var portalSettings = new PortalSettings(portalId == Null.NullInteger ? Host.HostPortalID : portalId); + var portalAlias = this.portalAliasService.GetPortalAliasesByPortalId(portalId == Null.NullInteger ? Host.HostPortalID : portalId) + .OrderByDescending(a => a.IsPrimary) + .First(); + var sslEnabled = portalSettings.SSLEnabled && portalSettings.SSLSetup == DotNetNuke.Abstractions.Security.SiteSslSetup.On; + + var siteUrl = $"{(sslEnabled ? "https" : "http")}://{portalAlias.HttpAlias}"; + + return string.Format(Constants.CallbackUrl, siteUrl, portalId); + } + + /// + public IList GetSettings(int portalId) + { + return portalId > Null.NullInteger ? this.GetSettingsFromPortal(portalId) : this.GetSettingsFromHost(); + } + + /// + public bool UpdateSettings(int portalId, IDictionary settings, out IList errorMessages) + { + errorMessages = new List(); + bool changed; + + if (portalId == Null.NullInteger) + { + changed = this.UpdateHostSettings(settings); + } + else + { + changed = this.UpdatePortalSettings(portalId, settings); + } + + if (changed) + { + this.DeleteSetting(portalId, Constants.AuthenticationSettingName); + } + + return changed; + } + + /// + public void Authorize(int portalId, IOAuth2SmtpClient smtpClient) + { + if (!this.IsAuthorized(portalId)) + { + return; + } + + var clientApplication = CreateClientApplication(this, this.hostSettingsService, portalId); + var account = clientApplication.GetAccountsAsync().Result.First(); + var scopes = GetAuthenticationScopes(); + var result = clientApplication.AcquireTokenSilent(scopes, account).ExecuteAsync().Result; + if (result != null) + { + var username = result.Account.Username; + var accessToken = result.AccessToken; + + smtpClient.Authenticate(username, accessToken); + } + } + + /// + public async Task AuthorizeAsync(int portalId, IOAuth2SmtpClient smtpClient, CancellationToken cancellationToken = default) + { + if (await this.IsAuthorizedAsync(portalId, cancellationToken) == false) + { + return; + } + + var clientApplication = CreateClientApplication(this, this.hostSettingsService, portalId); + var accounts = await clientApplication.GetAccountsAsync(cancellationToken); + var account = accounts.First(); + var scopes = GetAuthenticationScopes(); + var result = await clientApplication.AcquireTokenSilent(scopes, account).ExecuteAsync(cancellationToken); + if (result != null) + { + var username = result.Account.Username; + var accessToken = result.AccessToken; + + await smtpClient.AuthenticateAsync(username, accessToken, cancellationToken); + } + } + + /// Create the authentication client application. + /// The SMTP OAuth controller. + /// The host settings service. + /// The portal id. + /// The client application. + internal static ConfidentialClientApplication CreateClientApplication(ISmtpOAuthController smtpOAuthController, IHostSettingsService hostSettingsService, int portalId) + { + return CreateClientApplication(smtpOAuthController.GetOAuthProvider(Constants.Name), hostSettingsService, portalId); + } + + /// Get the authentication scopes list. + /// The scopes. + internal static IList GetAuthenticationScopes() + { + return new[] { "https://outlook.office365.com/.default", }; + } + + private static ConfidentialClientApplication CreateClientApplication(ISmtpOAuthProvider authProvider, IHostSettingsService hostSettingsService, int portalId) + { + var settings = authProvider.GetSettings(portalId); + var tenantId = settings.FirstOrDefault(i => i.Name == Constants.TenantIdSettingName)?.Value ?? string.Empty; + var clientId = settings.FirstOrDefault(i => i.Name == Constants.ClientIdSettingName)?.Value ?? string.Empty; + var clientSecret = settings.FirstOrDefault(i => i.Name == Constants.ClientSecretSettingName)?.Value ?? string.Empty; + + if (string.IsNullOrWhiteSpace(tenantId) || + string.IsNullOrWhiteSpace(clientId) || + string.IsNullOrWhiteSpace(clientSecret)) + { + return null; + } + + var redirectUrl = authProvider.GetAuthorizeUrl(portalId); + var questionMarkIndex = redirectUrl.IndexOf('?'); + if (questionMarkIndex > -1) + { + redirectUrl = redirectUrl.Substring(0, questionMarkIndex); + } + + var options = new ConfidentialClientApplicationOptions + { + TenantId = tenantId, + ClientId = clientId, + ClientSecret = clientSecret, + RedirectUri = redirectUrl, + Instance = Constants.AzureInstance, + }; + var clientApplication = (ConfidentialClientApplication)ConfidentialClientApplicationBuilder + .CreateWithApplicationOptions(options) + .Build(); + + var tokenCacheHelper = new TokenCacheHelper(portalId, hostSettingsService); + tokenCacheHelper.EnableSerialization(clientApplication.UserTokenCache); + + return clientApplication; + } + + private IList GetSettingsFromPortal(int portalId) + { + var portalSettings = PortalController.Instance.GetPortalSettings(portalId); + if (portalSettings == null) + { + throw new ArgumentException("Invalid portal Id."); + } + + var tenantId = portalSettings.GetValueOrDefault(Constants.TenantIdSettingName, string.Empty); + var clientId = portalSettings.GetValueOrDefault(Constants.ClientIdSettingName, string.Empty); + var clientSecret = portalSettings.GetValueOrDefault(Constants.ClientSecretSettingName, string.Empty); + if (!string.IsNullOrWhiteSpace(clientSecret)) + { + clientSecret = PortalSecurity.Instance.Decrypt(Config.GetDecryptionkey(), clientSecret); + } + + return new List + { + new SmtpOAuthSetting + { + Name = Constants.TenantIdSettingName, + Value = tenantId, + Label = Localization.GetString("TenantId", Constants.LocalResourcesFile), + Help = Localization.GetString("TenantId.Help", Constants.LocalResourcesFile), + IsRequired = true, + }, + new SmtpOAuthSetting + { + Name = Constants.ClientIdSettingName, + Value = clientId, + Label = Localization.GetString("ClientId", Constants.LocalResourcesFile), + Help = Localization.GetString("ClientId.Help", Constants.LocalResourcesFile), + IsRequired = true, + }, + new SmtpOAuthSetting + { + Name = Constants.ClientSecretSettingName, + Value = clientSecret, + Label = Localization.GetString("ClientSecret", Constants.LocalResourcesFile), + Help = Localization.GetString("ClientSecret.Help", Constants.LocalResourcesFile), + IsSecure = true, + IsRequired = true, + }, + }; + } + + private IList GetSettingsFromHost() + { + var tenantId = this.hostSettingsService.GetString(Constants.TenantIdSettingName, string.Empty); + var clientId = this.hostSettingsService.GetString(Constants.ClientIdSettingName, string.Empty); + var clientSecret = this.hostSettingsService.GetString(Constants.ClientSecretSettingName, string.Empty); + if (!string.IsNullOrWhiteSpace(clientSecret)) + { + clientSecret = PortalSecurity.Instance.Decrypt(Config.GetDecryptionkey(), clientSecret); + } + + return new List + { + new SmtpOAuthSetting + { + Name = Constants.TenantIdSettingName, + Value = tenantId, + Label = Localization.GetString("TenantId", Constants.LocalResourcesFile), + Help = Localization.GetString("TenantId.Help", Constants.LocalResourcesFile), + IsRequired = true, + }, + new SmtpOAuthSetting + { + Name = Constants.ClientIdSettingName, + Value = clientId, + Label = Localization.GetString("ClientId", Constants.LocalResourcesFile), + Help = Localization.GetString("ClientId.Help", Constants.LocalResourcesFile), + IsRequired = true, + }, + new SmtpOAuthSetting + { + Name = Constants.ClientSecretSettingName, + Value = clientSecret, + Label = Localization.GetString("ClientSecret", Constants.LocalResourcesFile), + Help = Localization.GetString("ClientSecret.Help", Constants.LocalResourcesFile), + IsSecure = true, + IsRequired = true, + }, + }; + } + + private bool UpdateHostSettings(IDictionary settings) + { + var tenantId = this.GetSetting(Null.NullInteger, Constants.TenantIdSettingName); + var clientId = this.GetSetting(Null.NullInteger, Constants.ClientIdSettingName); + var clientSecret = this.GetSetting(Null.NullInteger, Constants.ClientSecretSettingName); + + var changed = false; + if (settings.ContainsKey(Constants.TenantIdSettingName) && settings[Constants.TenantIdSettingName] != tenantId) + { + this.hostSettingsService.Update(Constants.TenantIdSettingName, settings[Constants.TenantIdSettingName], false); + changed = true; + } + + if (settings.ContainsKey(Constants.ClientIdSettingName) && settings[Constants.ClientIdSettingName] != clientId) + { + this.hostSettingsService.Update(Constants.ClientIdSettingName, settings[Constants.ClientIdSettingName], false); + changed = true; + } + + if (settings.ContainsKey(Constants.ClientSecretSettingName) && settings[Constants.ClientSecretSettingName] != clientSecret) + { + var encryptedSecret = PortalSecurity.Instance.Encrypt(Config.GetDecryptionkey(), settings[Constants.ClientSecretSettingName]); + this.hostSettingsService.Update(Constants.ClientSecretSettingName, encryptedSecret, false); + changed = true; + } + + if (changed) + { + DataCache.ClearCache(); + } + + return changed; + } + + private bool UpdatePortalSettings(int portalId, IDictionary settings) + { + var tenantId = this.GetSetting(portalId, Constants.TenantIdSettingName); + var clientId = this.GetSetting(portalId, Constants.ClientIdSettingName); + var clientSecret = this.GetSetting(portalId, Constants.ClientSecretSettingName); + + var changed = false; + if (settings.ContainsKey(Constants.TenantIdSettingName) && settings[Constants.TenantIdSettingName] != tenantId) + { + PortalController.UpdatePortalSetting(portalId, Constants.TenantIdSettingName, settings[Constants.TenantIdSettingName], false); + changed = true; + } + + if (settings.ContainsKey(Constants.ClientIdSettingName) && settings[Constants.ClientIdSettingName] != clientId) + { + PortalController.UpdatePortalSetting(portalId, Constants.ClientIdSettingName, settings[Constants.ClientIdSettingName], false); + changed = true; + } + + if (settings.ContainsKey(Constants.ClientSecretSettingName) && settings[Constants.ClientSecretSettingName] != clientSecret) + { + var encryptedSecret = PortalSecurity.Instance.Encrypt(Config.GetDecryptionkey(), settings[Constants.ClientSecretSettingName]); + PortalController.UpdatePortalSetting(portalId, Constants.ClientSecretSettingName, encryptedSecret, false); + changed = true; + } + + if (changed) + { + DataCache.ClearPortalCache(portalId, false); + } + + return changed; + } + + private string GetSetting(int portalId, string settingName) + { + var settings = this.GetSettings(portalId); + var setting = settings.FirstOrDefault(i => i.Name == settingName); + + return setting?.Value ?? string.Empty; + } + + private void DeleteSetting(int portalId, string settingName) + { + if (portalId == Null.NullInteger) + { + this.hostSettingsService.Update(settingName, string.Empty, false); + } + else + { + PortalController.UpdatePortalSetting(portalId, settingName, string.Empty, false); + } + } +} diff --git a/DNN Platform/Providers/SmtpOAuthProviders/ExchangeOnlineAuthProvider/Components/TokenCacheHelper.cs b/DNN Platform/Providers/SmtpOAuthProviders/ExchangeOnlineAuthProvider/Components/TokenCacheHelper.cs new file mode 100644 index 00000000000..9d2eab4ce46 --- /dev/null +++ b/DNN Platform/Providers/SmtpOAuthProviders/ExchangeOnlineAuthProvider/Components/TokenCacheHelper.cs @@ -0,0 +1,78 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + +namespace Dnn.ExchangeOnlineAuthProvider.Components; + +using System.Text; + +using DotNetNuke.Abstractions.Application; +using DotNetNuke.Common.Utilities; +using DotNetNuke.Entities.Portals; + +using Microsoft.Identity.Client; + +/// The token cache helper. +public class TokenCacheHelper +{ + private readonly IHostSettingsService hostSettingsService; + private readonly int portalId; + + /// Initializes a new instance of the class. + /// The portal ID. + /// The host settings service. + public TokenCacheHelper(int portalId, IHostSettingsService hostSettingsService) + { + this.portalId = portalId; + this.hostSettingsService = hostSettingsService; + } + + /// Enable the token cache. + /// The token cache instance. + public void EnableSerialization(ITokenCache tokenCache) + { + tokenCache.SetBeforeAccess(this.BeforeAccessNotification); + tokenCache.SetAfterAccess(this.AfterAccessNotification); + } + + private void BeforeAccessNotification(TokenCacheNotificationArgs args) + { + var authentication = this.GetAuthenticationData(); + if (!string.IsNullOrEmpty(authentication)) + { + args.TokenCache.DeserializeMsalV3(Encoding.UTF8.GetBytes(authentication)); + } + } + + private void AfterAccessNotification(TokenCacheNotificationArgs args) + { + if (args.HasStateChanged) + { + byte[] data = args.TokenCache.SerializeMsalV3(); + this.UpdateAuthenticationData(data); + } + } + + private string GetAuthenticationData() + { + if (this.portalId == Null.NullInteger) + { + return this.hostSettingsService.GetEncryptedString(Constants.AuthenticationSettingName, Config.GetDecryptionkey()); + } + + return PortalController.GetEncryptedString(Constants.AuthenticationSettingName, this.portalId, Config.GetDecryptionkey()); + } + + private void UpdateAuthenticationData(byte[] data) + { + var settingValue = Encoding.UTF8.GetString(data); + if (this.portalId == Null.NullInteger) + { + this.hostSettingsService.UpdateEncryptedString(Constants.AuthenticationSettingName, settingValue, Config.GetDecryptionkey()); + } + else + { + PortalController.UpdateEncryptedString(this.portalId, Constants.AuthenticationSettingName, settingValue, Config.GetDecryptionkey()); + } + } +} diff --git a/DNN Platform/Providers/SmtpOAuthProviders/ExchangeOnlineAuthProvider/Dnn.ExchangeOnlineAuthProvider.csproj b/DNN Platform/Providers/SmtpOAuthProviders/ExchangeOnlineAuthProvider/Dnn.ExchangeOnlineAuthProvider.csproj new file mode 100644 index 00000000000..041c83a0e81 --- /dev/null +++ b/DNN Platform/Providers/SmtpOAuthProviders/ExchangeOnlineAuthProvider/Dnn.ExchangeOnlineAuthProvider.csproj @@ -0,0 +1,172 @@ + + + + true + + + Debug + AnyCPU + 8.0.30703 + 2.0 + {37C3B4D3-AFAD-490B-9541-068A098E846F} + Library + Properties + Dnn.ExchangeOnlineAuthProvider + Dnn.ExchangeOnlineAuthProvider + v4.7.2 + 512 + + true + + + true + full + false + bin\ + DEBUG;TRACE + prompt + 4 + bin\Dnn.ExchangeOnlineAuthProvider.xml + latest + 1591 + true + + + pdbonly + true + bin\ + TRACE + prompt + 4 + bin\Dnn.ExchangeOnlineAuthProvider.xml + latest + 1591 + true + + + true + full + false + bin\ + DEBUG;TRACE;CLOUD;CLOUD_DEBUG + prompt + 4 + bin\Dnn.ExchangeOnlineAuthProvider.xml + latest + 1591 + true + + + pdbonly + true + bin\ + TRACE;CLOUD;CLOUD_RELEASE + prompt + 4 + bin\Dnn.ExchangeOnlineAuthProvider.xml + latest + 1591 + true + + + + ..\..\..\..\packages\Portable.BouncyCastle.1.9.0\lib\net40\BouncyCastle.Crypto.dll + + + ..\..\..\..\packages\MailKit.2.15.0\lib\net47\MailKit.dll + + + + ..\..\..\..\packages\Microsoft.Extensions.DependencyInjection.Abstractions.2.1.1\lib\netstandard2.0\Microsoft.Extensions.DependencyInjection.Abstractions.dll + + + ..\..\..\..\packages\Microsoft.Identity.Client.4.49.1\lib\net461\Microsoft.Identity.Client.dll + + + ..\..\..\..\packages\Microsoft.IdentityModel.Abstractions.6.22.0\lib\net472\Microsoft.IdentityModel.Abstractions.dll + + + ..\..\..\..\packages\MimeKit.2.15.1\lib\net47\MimeKit.dll + + + ..\..\..\..\packages\Newtonsoft.Json.13.0.3\lib\net45\Newtonsoft.Json.dll + + + + ..\..\..\..\packages\System.Buffers.4.5.1\lib\net461\System.Buffers.dll + + + + + + + + ..\..\..\..\packages\Microsoft.AspNet.WebApi.Client.5.2.9\lib\net45\System.Net.Http.Formatting.dll + + + + + ..\..\..\..\packages\Microsoft.AspNet.WebApi.Core.5.2.9\lib\net45\System.Web.Http.dll + + + ..\..\..\..\packages\Microsoft.AspNet.WebApi.WebHost.5.2.9\lib\net45\System.Web.Http.WebHost.dll + + + + + + + + + + SolutionInfo.cs + + + Authorize.aspx + ASPXCodeBehind + + + + + + + + stylecop.json + + + + + ASPXCodeBehind + + + + + + + + + Designer + + + + + + + + + {6928a9b1-f88a-4581-a132-d3eb38669bb0} + DotNetNuke.Abstractions + + + {ee1329fe-fd88-4e1a-968c-345e394ef080} + DotNetNuke.Web + + + {6b29aded-7b56-4484-bea5-c0e09079535b} + DotNetNuke.Library + + + + + + \ No newline at end of file diff --git a/DNN Platform/Providers/SmtpOAuthProviders/ExchangeOnlineAuthProvider/ExchangeOnlineAuthProvider.dnn b/DNN Platform/Providers/SmtpOAuthProviders/ExchangeOnlineAuthProvider/ExchangeOnlineAuthProvider.dnn new file mode 100644 index 00000000000..619b2391c98 --- /dev/null +++ b/DNN Platform/Providers/SmtpOAuthProviders/ExchangeOnlineAuthProvider/ExchangeOnlineAuthProvider.dnn @@ -0,0 +1,49 @@ + + + + Exchange Online SMTP OAuth Provider + The provider allows you to config the SMTP client to send emails with Microsoft exchange online service. + ~/Icons/Sigma/Extensions_32x32_Standard.png + + 09.12.00 + + + .NET Foundation and Contributors + DNN Community + https://dnncommunity.org + info@dnncommunity.org + + + + true + + + + + bin + Dnn.ExchangeOnlineAuthProvider.dll + + + bin + Microsoft.Identity.Client.dll + 4.49.1.0 + + + bin + Microsoft.IdentityModel.Abstractions.dll + 6.22.0.30727 + + + + + + Providers\SmtpOAuthProviders\ExchangeOnline + + Resources.zip + + + + + + + \ No newline at end of file diff --git a/DNN Platform/Providers/SmtpOAuthProviders/ExchangeOnlineAuthProvider/Properties/AssemblyInfo.cs b/DNN Platform/Providers/SmtpOAuthProviders/ExchangeOnlineAuthProvider/Properties/AssemblyInfo.cs new file mode 100644 index 00000000000..b3d54de5eb7 --- /dev/null +++ b/DNN Platform/Providers/SmtpOAuthProviders/ExchangeOnlineAuthProvider/Properties/AssemblyInfo.cs @@ -0,0 +1,12 @@ +// +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the MIT License. See LICENSE file in the project root for full license information. +// +#region Usings +using System; +using System.Reflection; +#endregion + +[assembly: AssemblyTitle("DotNetNuke")] + +[assembly: CLSCompliant(true)] diff --git a/DNN Platform/Providers/SmtpOAuthProviders/ExchangeOnlineAuthProvider/Provider.build b/DNN Platform/Providers/SmtpOAuthProviders/ExchangeOnlineAuthProvider/Provider.build new file mode 100644 index 00000000000..6ef5b7cea4b --- /dev/null +++ b/DNN Platform/Providers/SmtpOAuthProviders/ExchangeOnlineAuthProvider/Provider.build @@ -0,0 +1,29 @@ + + + $(MSBuildProjectDirectory)\..\..\..\.. + + + + zip + ExchangeOnlineAuthProvider + DNNCE_ExchangeOnlineAuthProvider + + $(WebsiteInstallPath)\Provider + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/DNN Platform/Providers/SmtpOAuthProviders/ExchangeOnlineAuthProvider/Services/ServiceRouteMapper.cs b/DNN Platform/Providers/SmtpOAuthProviders/ExchangeOnlineAuthProvider/Services/ServiceRouteMapper.cs new file mode 100644 index 00000000000..745621ee0e9 --- /dev/null +++ b/DNN Platform/Providers/SmtpOAuthProviders/ExchangeOnlineAuthProvider/Services/ServiceRouteMapper.cs @@ -0,0 +1,21 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + +namespace Dnn.ExchangeOnlineAuthProvider.Services; + +using DotNetNuke.Web.Api; + +/// +public class ServiceRouteMapper : IServiceRouteMapper +{ + /// + public void RegisterRoutes(IMapRoute routeManager) + { + routeManager.MapHttpRoute( + "ExchangeOnlineAuth", + "default", + "{controller}/{action}", + new[] { "Dnn.ExchangeOnlineAuthProvider.Services" }); + } +} diff --git a/DNN Platform/Providers/SmtpOAuthProviders/ExchangeOnlineAuthProvider/Services/ServicesController.cs b/DNN Platform/Providers/SmtpOAuthProviders/ExchangeOnlineAuthProvider/Services/ServicesController.cs new file mode 100644 index 00000000000..ce39933848c --- /dev/null +++ b/DNN Platform/Providers/SmtpOAuthProviders/ExchangeOnlineAuthProvider/Services/ServicesController.cs @@ -0,0 +1,13 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + +namespace Dnn.ExchangeOnlineAuthProvider.Services; + +using DotNetNuke.Web.Api; + +/// +[DnnAuthorize] +public class ServicesController : DnnApiController +{ +} diff --git a/DNN Platform/Providers/SmtpOAuthProviders/ExchangeOnlineAuthProvider/app.config b/DNN Platform/Providers/SmtpOAuthProviders/ExchangeOnlineAuthProvider/app.config new file mode 100644 index 00000000000..eac412fe488 --- /dev/null +++ b/DNN Platform/Providers/SmtpOAuthProviders/ExchangeOnlineAuthProvider/app.config @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/DNN Platform/Providers/SmtpOAuthProviders/ExchangeOnlineAuthProvider/license.txt b/DNN Platform/Providers/SmtpOAuthProviders/ExchangeOnlineAuthProvider/license.txt new file mode 100644 index 00000000000..67ea9ae6bb8 --- /dev/null +++ b/DNN Platform/Providers/SmtpOAuthProviders/ExchangeOnlineAuthProvider/license.txt @@ -0,0 +1,20 @@ +
      +

      License

      +

      + Copyright (c) .NET Foundation and Contributors
      + All Rights Reserved +

      +

      + Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated + documentation files (the "Software"), to deal in the Software without restriction, including without limitation + the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and + to permit persons to whom the Software is furnished to do so, subject to the following conditions: +

      +

      + The above copyright notice and this permission notice shall be included in all copies or substantial portions + of the Software. +

      +

      + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +

      +
      \ No newline at end of file diff --git a/DNN Platform/Providers/SmtpOAuthProviders/ExchangeOnlineAuthProvider/packages.config b/DNN Platform/Providers/SmtpOAuthProviders/ExchangeOnlineAuthProvider/packages.config new file mode 100644 index 00000000000..ff5a48b1284 --- /dev/null +++ b/DNN Platform/Providers/SmtpOAuthProviders/ExchangeOnlineAuthProvider/packages.config @@ -0,0 +1,16 @@ + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/DNN Platform/Providers/SmtpOAuthProviders/ExchangeOnlineAuthProvider/releaseNotes.txt b/DNN Platform/Providers/SmtpOAuthProviders/ExchangeOnlineAuthProvider/releaseNotes.txt new file mode 100644 index 00000000000..e1e23a4bfc6 --- /dev/null +++ b/DNN Platform/Providers/SmtpOAuthProviders/ExchangeOnlineAuthProvider/releaseNotes.txt @@ -0,0 +1 @@ +There are no release notes for this version. diff --git a/DNN Platform/Providers/SmtpOAuthProviders/GoogleMailAuthProvider/App_LocalResources/SharedResources.resx b/DNN Platform/Providers/SmtpOAuthProviders/GoogleMailAuthProvider/App_LocalResources/SharedResources.resx new file mode 100644 index 00000000000..b7c650fb016 --- /dev/null +++ b/DNN Platform/Providers/SmtpOAuthProviders/GoogleMailAuthProvider/App_LocalResources/SharedResources.resx @@ -0,0 +1,141 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + The email address of your gmail account. + + + Email + + + The client id of your google oauth application. + + + Client Id + + + The client secret of your google oauth application. + + + Client Secret + + + Google Mail + + \ No newline at end of file diff --git a/DNN Platform/Providers/SmtpOAuthProviders/GoogleMailAuthProvider/Authorize.aspx b/DNN Platform/Providers/SmtpOAuthProviders/GoogleMailAuthProvider/Authorize.aspx new file mode 100644 index 00000000000..aa48ec2449d --- /dev/null +++ b/DNN Platform/Providers/SmtpOAuthProviders/GoogleMailAuthProvider/Authorize.aspx @@ -0,0 +1 @@ +<%@ Page Language="C#" AutoEventWireup="false" Inherits="Dnn.GoogleMailAuthProvider.Authorize, Dnn.GoogleMailAuthProvider" CodeBehind="Authorize.aspx.cs" Async="true" %> \ No newline at end of file diff --git a/DNN Platform/Providers/SmtpOAuthProviders/GoogleMailAuthProvider/Authorize.aspx.cs b/DNN Platform/Providers/SmtpOAuthProviders/GoogleMailAuthProvider/Authorize.aspx.cs new file mode 100644 index 00000000000..bfd6fc7908d --- /dev/null +++ b/DNN Platform/Providers/SmtpOAuthProviders/GoogleMailAuthProvider/Authorize.aspx.cs @@ -0,0 +1,114 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + +namespace Dnn.GoogleMailAuthProvider; + +using System; +using System.Linq; +using System.Text.RegularExpressions; +using System.Threading; +using System.Threading.Tasks; +using System.Web.UI; + +using Dnn.GoogleMailAuthProvider.Components; +using DotNetNuke.Abstractions.Application; +using DotNetNuke.Common; +using DotNetNuke.Common.Extensions; +using DotNetNuke.Common.Utilities; +using DotNetNuke.Services.Mail.OAuth; +using Google.Apis.Auth.OAuth2.Web; +using Microsoft.Extensions.DependencyInjection; + +/// Google OAuth callback. +public abstract class Authorize : Page +{ + private readonly ISmtpOAuthController smtpOAuthController; + private readonly IHostSettingsService hostSettingsService; + + /// Initializes a new instance of the class. + protected Authorize() + : this(null, null) + { + } + + /// Initializes a new instance of the class. + /// The SMTP OAuth controller. + /// The host settings service. + protected Authorize(ISmtpOAuthController smtpOAuthController, IHostSettingsService hostSettingsService) + { + if (smtpOAuthController != null) + { + this.smtpOAuthController = smtpOAuthController; + this.hostSettingsService = hostSettingsService; + } + else + { + var serviceProvider = HttpContextSource.Current.GetScope().ServiceProvider; + this.smtpOAuthController = serviceProvider.GetRequiredService(); + this.hostSettingsService = hostSettingsService ?? serviceProvider.GetRequiredService(); + } + } + + /// OnLoad event. + /// Event. + protected override void OnLoad(EventArgs e) + { + base.OnLoad(e); + this.RegisterAsyncTask(new PageAsyncTask(this.OnLoadAsync)); + } + + private async Task OnLoadAsync(CancellationToken cancellationToken) + { + var portalId = Null.NullInteger; + if (this.Request.QueryString["state"] != null) + { + var portalIdStr = RegexUtils.GetCachedRegex("portal_([0-9\\-]+?)_", RegexOptions.IgnoreCase).Match(this.Request.QueryString["state"]).Groups[1].Value; + if (!string.IsNullOrWhiteSpace(portalIdStr)) + { + portalId = Convert.ToInt32(portalIdStr); + } + } + + var authProvider = this.smtpOAuthController.GetOAuthProvider(Constants.Name); + + var settings = authProvider.GetSettings(portalId); + var accountEmail = settings.FirstOrDefault(i => i.Name == Constants.AccountEmailSettingName)?.Value ?? string.Empty; + + var codeFlow = GoogleMailOAuthProvider.CreateAuthorizationCodeFlow(this.smtpOAuthController, this.hostSettingsService, portalId); + if (codeFlow == null || await authProvider.IsAuthorizedAsync(portalId, cancellationToken)) + { + this.CloseWindow(); + return; + } + + var uri = this.Request.Url.ToString(); + var questionMarkIndex = uri.IndexOf('?'); + if (questionMarkIndex > -1) + { + uri = uri.Substring(0, questionMarkIndex); + } + + var code = this.Request["code"]; + if (code != null) + { + _ = await codeFlow.ExchangeCodeForTokenAsync(accountEmail, code, uri, cancellationToken); + } + else + { + var result = await new AuthorizationCodeWebApp(codeFlow, uri, this.Request.QueryString["state"]).AuthorizeAsync(accountEmail, cancellationToken); + if (result.RedirectUri != null) + { + // Redirect the user to the authorization server. + this.Response.Redirect(result.RedirectUri, true); + } + } + + this.CloseWindow(); + } + + private void CloseWindow() + { + this.Response.Write(""); + } +} diff --git a/DNN Platform/Providers/SmtpOAuthProviders/GoogleMailAuthProvider/Components/Constants.cs b/DNN Platform/Providers/SmtpOAuthProviders/GoogleMailAuthProvider/Components/Constants.cs new file mode 100644 index 00000000000..2bf12ddc11c --- /dev/null +++ b/DNN Platform/Providers/SmtpOAuthProviders/GoogleMailAuthProvider/Components/Constants.cs @@ -0,0 +1,30 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + +namespace Dnn.GoogleMailAuthProvider.Components; + +/// Google SMTP OAuth constants. +internal class Constants +{ + /// The provider name. + public const string Name = "GoogleMail"; + + /// The client id setting name. + public const string ClientIdSettingName = "gmailauth_clientId"; + + /// The client secret setting name. + public const string ClientSecretSettingName = "gmailauth_clientSecret"; + + /// The account email setting name. + public const string AccountEmailSettingName = "gmailauth_username"; + + /// The data store setting name. + public const string DataStoreSettingName = "gmailauth_{0}_datastore"; + + /// The authorize callback URL. + public const string CallbackUrl = "{0}/Providers/SmtpOAuthProviders/GoogleMail/Authorize.aspx?state=portal_{1}_"; + + /// The local resources file path. + public const string LocalResourcesFile = "~/Providers/SmtpOAuthProviders/GoogleMail/App_LocalResources/SharedResources.resx"; +} diff --git a/DNN Platform/Providers/SmtpOAuthProviders/GoogleMailAuthProvider/Components/GoogleCredentialDataStore.cs b/DNN Platform/Providers/SmtpOAuthProviders/GoogleMailAuthProvider/Components/GoogleCredentialDataStore.cs new file mode 100644 index 00000000000..d84430bd066 --- /dev/null +++ b/DNN Platform/Providers/SmtpOAuthProviders/GoogleMailAuthProvider/Components/GoogleCredentialDataStore.cs @@ -0,0 +1,159 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + +namespace Dnn.GoogleMailAuthProvider.Components; + +using System; +using System.Collections.Generic; +using System.Threading.Tasks; + +using DotNetNuke.Abstractions.Application; +using DotNetNuke.Common.Utilities; +using DotNetNuke.Entities.Portals; + +using Google.Apis.Json; +using Google.Apis.Util.Store; + +/// Google credentials data store class. +public class GoogleCredentialDataStore : IDataStore +{ + private readonly IHostSettingsService hostSettingsService; + private readonly int portalId; + + /// + /// Initializes a new instance of the class. + /// + /// The portal id. + /// The host settings service. + public GoogleCredentialDataStore(int portalId, IHostSettingsService hostSettingsService) + { + this.portalId = portalId; + this.hostSettingsService = hostSettingsService; + } + + /// + public Task ClearAsync() + { + var settingName = string.Format(Constants.DataStoreSettingName, this.portalId); + if (this.portalId == Null.NullInteger) + { + this.hostSettingsService.Update(settingName, null, true); + } + else + { + PortalController.UpdatePortalSetting(this.portalId, settingName, null, true); + } + + return Task.CompletedTask; + } + + /// + public Task DeleteAsync(string key) + { + if (string.IsNullOrEmpty(key)) + { + throw new ArgumentException("Key MUST have a value"); + } + + var dataStore = this.LoadDataStore(); + var settingName = GenerateStoredKey(key, typeof(T)); + if (dataStore.ContainsKey(settingName)) + { + dataStore.Remove(settingName); + } + + this.SaveDataStore(dataStore); + + return Task.CompletedTask; + } + + /// + public Task GetAsync(string key) + { + if (string.IsNullOrEmpty(key)) + { + throw new ArgumentException("Key MUST have a value"); + } + + var dataStore = this.LoadDataStore(); + var settingName = GenerateStoredKey(key, typeof(T)); + if (!dataStore.TryGetValue(settingName, out var settingValue)) + { + settingValue = string.Empty; + } + + if (string.IsNullOrWhiteSpace(settingValue)) + { + return Task.FromResult(default(T)); + } + + try + { + return Task.FromResult(NewtonsoftJsonSerializer.Instance.Deserialize(settingValue)); + } + catch (Exception ex) + { + return Task.FromException(ex); + } + } + + /// + public Task StoreAsync(string key, T value) + { + if (string.IsNullOrEmpty(key)) + { + throw new ArgumentException("Key MUST have a value"); + } + + var dataStore = this.LoadDataStore(); + var settingName = GenerateStoredKey(key, typeof(T)); + var settingValue = NewtonsoftJsonSerializer.Instance.Serialize(value); + dataStore[settingName] = settingValue; + this.SaveDataStore(dataStore); + + return Task.CompletedTask; + } + + private static string GenerateStoredKey(string key, Type t) + { + return $"{t.FullName}-{key}"; + } + + private IDictionary LoadDataStore() + { + var settingName = string.Format(Constants.DataStoreSettingName, this.portalId); + string settingValue; + + if (this.portalId == Null.NullInteger) + { + settingValue = this.hostSettingsService.GetEncryptedString(settingName, Config.GetDecryptionkey()); + } + else + { + settingValue = PortalController.GetEncryptedString(settingName, this.portalId, Config.GetDecryptionkey()); + } + + if (string.IsNullOrWhiteSpace(settingValue)) + { + return new Dictionary(); + } + + return NewtonsoftJsonSerializer.Instance.Deserialize>(settingValue); + } + + private void SaveDataStore(IDictionary dataStore) + { + var settingName = string.Format(Constants.DataStoreSettingName, this.portalId); + var settingValue = NewtonsoftJsonSerializer.Instance.Serialize(dataStore); + + if (this.portalId == Null.NullInteger) + { + this.hostSettingsService.UpdateEncryptedString(settingName, settingValue, Config.GetDecryptionkey()); + } + else + { + PortalController.UpdateEncryptedString(this.portalId, settingName, settingValue, Config.GetDecryptionkey()); + } + } +} diff --git a/DNN Platform/Providers/SmtpOAuthProviders/GoogleMailAuthProvider/Components/GoogleMailOAuthProvider.cs b/DNN Platform/Providers/SmtpOAuthProviders/GoogleMailAuthProvider/Components/GoogleMailOAuthProvider.cs new file mode 100644 index 00000000000..aa40aae6d9e --- /dev/null +++ b/DNN Platform/Providers/SmtpOAuthProviders/GoogleMailAuthProvider/Components/GoogleMailOAuthProvider.cs @@ -0,0 +1,389 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + +namespace Dnn.GoogleMailAuthProvider.Components; + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; + +using DotNetNuke.Abstractions.Application; +using DotNetNuke.Abstractions.Portals; +using DotNetNuke.Collections; +using DotNetNuke.Common.Utilities; +using DotNetNuke.Entities.Host; +using DotNetNuke.Entities.Portals; +using DotNetNuke.Security; +using DotNetNuke.Services.Localization; +using DotNetNuke.Services.Mail.OAuth; + +using Google.Apis.Auth.OAuth2; +using Google.Apis.Auth.OAuth2.Flows; +using Google.Apis.Auth.OAuth2.Responses; +using Google.Apis.Util; + +/// +public class GoogleMailOAuthProvider : ISmtpOAuthProvider +{ + private readonly IHostSettingsService hostSettingsService; + private readonly IPortalAliasService portalAliasService; + + /// Initializes a new instance of the class. + /// The host settings service. + /// The portal alias service. + public GoogleMailOAuthProvider(IHostSettingsService hostSettingsService, IPortalAliasService portalAliasService) + { + this.hostSettingsService = hostSettingsService; + this.portalAliasService = portalAliasService; + } + + /// + public string Name => Constants.Name; + + /// + public string LocalizedName => Localization.GetSafeJSString(this.Name, Constants.LocalResourcesFile); + + /// + public bool IsAuthorized(int portalId) + { + return Task.Run(() => this.IsAuthorizedAsync(portalId)).GetAwaiter().GetResult(); + } + + /// + public async Task IsAuthorizedAsync(int portalId, CancellationToken cancellationToken = default) + { + var accountEmail = this.GetSetting(portalId, Constants.AccountEmailSettingName); + if (string.IsNullOrWhiteSpace(accountEmail)) + { + return false; + } + + var credential = await new GoogleCredentialDataStore(portalId, this.hostSettingsService).GetAsync(accountEmail); + + return !string.IsNullOrWhiteSpace(credential?.AccessToken); + } + + /// + public string GetAuthorizeUrl(int portalId) + { + var accountEmail = this.GetSetting(portalId, Constants.AccountEmailSettingName); + var clientId = this.GetSetting(portalId, Constants.ClientIdSettingName); + var clientSecret = this.GetSetting(portalId, Constants.ClientSecretSettingName); + + if (string.IsNullOrWhiteSpace(accountEmail) + || string.IsNullOrWhiteSpace(clientId) + || string.IsNullOrWhiteSpace(clientSecret)) + { + return string.Empty; + } + + var portalSettings = new PortalSettings(portalId == Null.NullInteger ? Host.HostPortalID : portalId); + var portalAlias = this.portalAliasService.GetPortalAliasesByPortalId(portalId == Null.NullInteger ? Host.HostPortalID : portalId) + .OrderByDescending(a => a.IsPrimary) + .First(); + var sslEnabled = portalSettings.SSLEnabled && portalSettings.SSLSetup == DotNetNuke.Abstractions.Security.SiteSslSetup.On; + + var siteUrl = $"{(sslEnabled ? "https" : "http")}://{portalAlias.HttpAlias}"; + + return string.Format(Constants.CallbackUrl, siteUrl, portalId); + } + + /// + public IList GetSettings(int portalId) + { + return portalId > Null.NullInteger ? GetSettingsFromPortal(portalId) : this.GetSettingsFromHost(); + } + + /// + public bool UpdateSettings(int portalId, IDictionary settings, out IList errorMessages) + { + errorMessages = new List(); + bool changed; + + if (portalId == Null.NullInteger) + { + changed = this.UpdateHostSettings(settings); + } + else + { + changed = this.UpdatePortalSettings(portalId, settings); + } + + if (changed) + { + var settingName = string.Format(Constants.DataStoreSettingName, portalId); + this.DeleteSetting(portalId, settingName); + } + + return changed; + } + + /// + public void Authorize(int portalId, IOAuth2SmtpClient smtpClient) + { + var settings = this.GetSettings(portalId); + var accountEmail = settings.FirstOrDefault(i => i.Name == Constants.AccountEmailSettingName)?.Value ?? string.Empty; + var codeFlow = this.CreateAuthorizationCodeFlow(portalId); + if (codeFlow == null) + { + return; + } + + var response = new GoogleCredentialDataStore(portalId, this.hostSettingsService).GetAsync(accountEmail).Result; + var credential = new UserCredential(codeFlow, accountEmail, response); + if (credential.Token.IsExpired(SystemClock.Default)) + { + _ = credential.RefreshTokenAsync(CancellationToken.None).Result; + } + + smtpClient.Authenticate(credential.UserId, credential.Token.AccessToken); + } + + /// + public async Task AuthorizeAsync(int portalId, IOAuth2SmtpClient smtpClient, CancellationToken cancellationToken) + { + var settings = this.GetSettings(portalId); + var accountEmail = settings.FirstOrDefault(i => i.Name == Constants.AccountEmailSettingName)?.Value ?? string.Empty; + var codeFlow = this.CreateAuthorizationCodeFlow(portalId); + if (codeFlow == null) + { + return; + } + + var response = await new GoogleCredentialDataStore(portalId, this.hostSettingsService).GetAsync(accountEmail); + var credential = new UserCredential(codeFlow, accountEmail, response); + if (credential.Token.IsExpired(SystemClock.Default)) + { + _ = await credential.RefreshTokenAsync(cancellationToken); + } + + await smtpClient.AuthenticateAsync(credential.UserId, credential.Token.AccessToken, cancellationToken); + } + + /// Create authorization code flow. + /// The SMTP OAuth controller. + /// The host settings service. + /// The portal ID. + /// The authorization code flow. + internal static IAuthorizationCodeFlow CreateAuthorizationCodeFlow(ISmtpOAuthController smtpOAuthController, IHostSettingsService hostSettingsService, int portalId) + { + return CreateAuthorizationCodeFlow(smtpOAuthController.GetOAuthProvider(Constants.Name), hostSettingsService, portalId); + } + + private static IAuthorizationCodeFlow CreateAuthorizationCodeFlow(ISmtpOAuthProvider authProvider, IHostSettingsService hostSettingsService, int portalId) + { + var settings = authProvider.GetSettings(portalId); + var accountEmail = settings.FirstOrDefault(i => i.Name == Constants.AccountEmailSettingName)?.Value ?? string.Empty; + var clientId = settings.FirstOrDefault(i => i.Name == Constants.ClientIdSettingName)?.Value ?? string.Empty; + var clientSecret = settings.FirstOrDefault(i => i.Name == Constants.ClientSecretSettingName)?.Value ?? string.Empty; + + if (string.IsNullOrWhiteSpace(accountEmail) || + string.IsNullOrWhiteSpace(clientId) || + string.IsNullOrWhiteSpace(clientSecret)) + { + return null; + } + + var clientSecrets = new ClientSecrets + { + ClientId = clientId, + ClientSecret = clientSecret, + }; + + return new GoogleAuthorizationCodeFlow( + new GoogleAuthorizationCodeFlow.Initializer + { + DataStore = new GoogleCredentialDataStore(portalId, hostSettingsService), + Scopes = new[] { "https://mail.google.com/", }, + ClientSecrets = clientSecrets, + Prompt = "consent", + }); + } + + private static IList GetSettingsFromPortal(int portalId) + { + var portalSettings = PortalController.Instance.GetPortalSettings(portalId); + if (portalSettings == null) + { + throw new ArgumentException("Invalid portal Id."); + } + + var accountEmail = portalSettings.GetValueOrDefault(Constants.AccountEmailSettingName, string.Empty); + var clientId = portalSettings.GetValueOrDefault(Constants.ClientIdSettingName, string.Empty); + var clientSecret = portalSettings.GetValueOrDefault(Constants.ClientSecretSettingName, string.Empty); + if (!string.IsNullOrWhiteSpace(clientSecret)) + { + clientSecret = PortalSecurity.Instance.Decrypt(Config.GetDecryptionkey(), clientSecret); + } + + return new List + { + new SmtpOAuthSetting + { + Name = Constants.AccountEmailSettingName, + Value = accountEmail, + Label = Localization.GetString("AccountEmail", Constants.LocalResourcesFile), + Help = Localization.GetString("AccountEmail.Help", Constants.LocalResourcesFile), + IsRequired = true, + }, + new SmtpOAuthSetting + { + Name = Constants.ClientIdSettingName, + Value = clientId, + Label = Localization.GetString("ClientId", Constants.LocalResourcesFile), + Help = Localization.GetString("ClientId.Help", Constants.LocalResourcesFile), + IsRequired = true, + }, + new SmtpOAuthSetting + { + Name = Constants.ClientSecretSettingName, + Value = clientSecret, + Label = Localization.GetString("ClientSecret", Constants.LocalResourcesFile), + Help = Localization.GetString("ClientSecret.Help", Constants.LocalResourcesFile), + IsSecure = true, + IsRequired = true, + }, + }; + } + + /// Create authorization code flow. + /// The portal ID. + /// The authorization code flow. + private IAuthorizationCodeFlow CreateAuthorizationCodeFlow(int portalId) + { + return CreateAuthorizationCodeFlow(this, this.hostSettingsService, portalId); + } + + private IList GetSettingsFromHost() + { + var hostSettings = this.hostSettingsService.GetSettingsDictionary().ToDictionary(i => i.Key, i => i.Value); + + var accountEmail = hostSettings.GetValueOrDefault(Constants.AccountEmailSettingName, string.Empty); + var clientId = hostSettings.GetValueOrDefault(Constants.ClientIdSettingName, string.Empty); + var clientSecret = hostSettings.GetValueOrDefault(Constants.ClientSecretSettingName, string.Empty); + if (!string.IsNullOrWhiteSpace(clientSecret)) + { + clientSecret = PortalSecurity.Instance.Decrypt(Config.GetDecryptionkey(), clientSecret); + } + + return new List + { + new SmtpOAuthSetting + { + Name = Constants.AccountEmailSettingName, + Value = accountEmail, + Label = Localization.GetString("AccountEmail", Constants.LocalResourcesFile), + Help = Localization.GetString("AccountEmail.Help", Constants.LocalResourcesFile), + IsRequired = true, + }, + new SmtpOAuthSetting + { + Name = Constants.ClientIdSettingName, + Value = clientId, + Label = Localization.GetString("ClientId", Constants.LocalResourcesFile), + Help = Localization.GetString("ClientId.Help", Constants.LocalResourcesFile), + IsRequired = true, + }, + new SmtpOAuthSetting + { + Name = Constants.ClientSecretSettingName, + Value = clientSecret, + Label = Localization.GetString("ClientSecret", Constants.LocalResourcesFile), + Help = Localization.GetString("ClientSecret.Help", Constants.LocalResourcesFile), + IsSecure = true, + IsRequired = true, + }, + }; + } + + private bool UpdateHostSettings(IDictionary settings) + { + var accountEmail = this.GetSetting(Null.NullInteger, Constants.AccountEmailSettingName); + var clientId = this.GetSetting(Null.NullInteger, Constants.ClientIdSettingName); + var clientSecret = this.GetSetting(Null.NullInteger, Constants.ClientSecretSettingName); + + var changed = false; + if (settings.ContainsKey(Constants.AccountEmailSettingName) && settings[Constants.AccountEmailSettingName] != accountEmail) + { + this.hostSettingsService.Update(Constants.AccountEmailSettingName, settings[Constants.AccountEmailSettingName], false); + changed = true; + } + + if (settings.ContainsKey(Constants.ClientIdSettingName) && settings[Constants.ClientIdSettingName] != clientId) + { + this.hostSettingsService.Update(Constants.ClientIdSettingName, settings[Constants.ClientIdSettingName], false); + changed = true; + } + + if (settings.ContainsKey(Constants.ClientSecretSettingName) && settings[Constants.ClientSecretSettingName] != clientSecret) + { + var encryptedSecret = PortalSecurity.Instance.Encrypt(Config.GetDecryptionkey(), settings[Constants.ClientSecretSettingName]); + this.hostSettingsService.Update(Constants.ClientSecretSettingName, encryptedSecret, false); + changed = true; + } + + if (changed) + { + DataCache.ClearCache(); + } + + return changed; + } + + private bool UpdatePortalSettings(int portalId, IDictionary settings) + { + var accountEmail = this.GetSetting(portalId, Constants.AccountEmailSettingName); + var clientId = this.GetSetting(portalId, Constants.ClientIdSettingName); + var clientSecret = this.GetSetting(portalId, Constants.ClientSecretSettingName); + + var changed = false; + if (settings.ContainsKey(Constants.AccountEmailSettingName) && settings[Constants.AccountEmailSettingName] != accountEmail) + { + PortalController.UpdatePortalSetting(portalId, Constants.AccountEmailSettingName, settings[Constants.AccountEmailSettingName], false); + changed = true; + } + + if (settings.ContainsKey(Constants.ClientIdSettingName) && settings[Constants.ClientIdSettingName] != clientId) + { + PortalController.UpdatePortalSetting(portalId, Constants.ClientIdSettingName, settings[Constants.ClientIdSettingName], false); + changed = true; + } + + if (settings.ContainsKey(Constants.ClientSecretSettingName) && settings[Constants.ClientSecretSettingName] != clientSecret) + { + var encryptedSecret = PortalSecurity.Instance.Encrypt(Config.GetDecryptionkey(), settings[Constants.ClientSecretSettingName]); + PortalController.UpdatePortalSetting(portalId, Constants.ClientSecretSettingName, encryptedSecret, false); + changed = true; + } + + if (changed) + { + DataCache.ClearPortalCache(portalId, false); + } + + return changed; + } + + private string GetSetting(int portalId, string settingName) + { + var settings = this.GetSettings(portalId); + var setting = settings.FirstOrDefault(i => i.Name == settingName); + + return setting?.Value ?? string.Empty; + } + + private void DeleteSetting(int portalId, string settingName) + { + if (portalId == Null.NullInteger) + { + this.hostSettingsService.Update(settingName, string.Empty, false); + } + else + { + PortalController.UpdatePortalSetting(portalId, settingName, string.Empty, false); + } + } +} diff --git a/DNN Platform/Providers/SmtpOAuthProviders/GoogleMailAuthProvider/Dnn.GoogleMailAuthProvider.csproj b/DNN Platform/Providers/SmtpOAuthProviders/GoogleMailAuthProvider/Dnn.GoogleMailAuthProvider.csproj new file mode 100644 index 00000000000..b332a79877f --- /dev/null +++ b/DNN Platform/Providers/SmtpOAuthProviders/GoogleMailAuthProvider/Dnn.GoogleMailAuthProvider.csproj @@ -0,0 +1,179 @@ + + + + true + + + Debug + AnyCPU + 8.0.30703 + 2.0 + {E5494C71-4472-4F19-AFB5-4D8902AA5670} + Library + Properties + Dnn.GoogleMailAuthProvider + Dnn.GoogleMailAuthProvider + v4.7.2 + 512 + + true + + + true + full + false + bin\ + DEBUG;TRACE + prompt + 4 + bin\Dnn.GoogleMailAuthProvider.xml + latest + 1591 + true + + + pdbonly + true + bin\ + TRACE + prompt + 4 + bin\Dnn.GoogleMailAuthProvider.xml + latest + 1591 + latest + true + + + true + full + false + bin\ + DEBUG;TRACE;CLOUD;CLOUD_DEBUG + prompt + 4 + bin\Dnn.GoogleMailAuthProvider.xml + latest + 1591 + true + + + pdbonly + true + bin\ + TRACE;CLOUD;CLOUD_RELEASE + prompt + 4 + bin\Dnn.GoogleMailAuthProvider.xml + latest + 1591 + latest + true + + + + ..\..\..\..\packages\Portable.BouncyCastle.1.9.0\lib\net40\BouncyCastle.Crypto.dll + + + ..\..\..\..\packages\Google.Apis.1.58.0\lib\net45\Google.Apis.dll + + + ..\..\..\..\packages\Google.Apis.Auth.1.58.0\lib\net461\Google.Apis.Auth.dll + + + ..\..\..\..\packages\Google.Apis.Auth.1.58.0\lib\net461\Google.Apis.Auth.PlatformServices.dll + + + ..\..\..\..\packages\Google.Apis.Core.1.58.0\lib\net45\Google.Apis.Core.dll + + + ..\..\..\..\packages\Google.Apis.1.58.0\lib\net45\Google.Apis.PlatformServices.dll + + + ..\..\..\..\packages\MailKit.2.15.0\lib\net47\MailKit.dll + + + ..\..\..\..\packages\Microsoft.Extensions.DependencyInjection.Abstractions.2.1.1\lib\netstandard2.0\Microsoft.Extensions.DependencyInjection.Abstractions.dll + + + ..\..\..\..\packages\MimeKit.2.15.1\lib\net47\MimeKit.dll + + + ..\..\..\..\packages\Newtonsoft.Json.13.0.3\lib\net45\Newtonsoft.Json.dll + + + + ..\..\..\..\packages\System.Buffers.4.5.1\lib\net461\System.Buffers.dll + + + + + + ..\..\..\..\packages\Microsoft.AspNet.WebApi.Client.5.2.9\lib\net45\System.Net.Http.Formatting.dll + + + + + ..\..\..\..\packages\Microsoft.AspNet.WebApi.Core.5.2.9\lib\net45\System.Web.Http.dll + + + ..\..\..\..\packages\Microsoft.AspNet.WebApi.WebHost.5.2.9\lib\net45\System.Web.Http.WebHost.dll + + + + + + + + + SolutionInfo.cs + + + Authorize.aspx + ASPXCodeBehind + + + + + + + + stylecop.json + + + + + ASPXCodeBehind + + + + + + + + + Designer + + + + + + + + + {6928a9b1-f88a-4581-a132-d3eb38669bb0} + DotNetNuke.Abstractions + + + {ee1329fe-fd88-4e1a-968c-345e394ef080} + DotNetNuke.Web + + + {6b29aded-7b56-4484-bea5-c0e09079535b} + DotNetNuke.Library + + + + + + \ No newline at end of file diff --git a/DNN Platform/Providers/SmtpOAuthProviders/GoogleMailAuthProvider/GoogleMailAuthProvider.dnn b/DNN Platform/Providers/SmtpOAuthProviders/GoogleMailAuthProvider/GoogleMailAuthProvider.dnn new file mode 100644 index 00000000000..ea48fce8001 --- /dev/null +++ b/DNN Platform/Providers/SmtpOAuthProviders/GoogleMailAuthProvider/GoogleMailAuthProvider.dnn @@ -0,0 +1,59 @@ + + + + Google Mail SMTP OAuth Provider + The provider allows you to config the SMTP client to send emails with gmail service. + ~/Icons/Sigma/Extensions_32x32_Standard.png + + 09.12.00 + + + .NET Foundation and Contributors + DNN Community + https://dnncommunity.org + info@dnncommunity.org + + + + true + + + + + bin + Dnn.GoogleMailAuthProvider.dll + + + bin + Google.Apis.Auth.dll + 1.58.0 + + + bin + Google.Apis.Auth.PlatformServices.dll + 1.58.0 + + + bin + Google.Apis.Core.dll + 1.58.0 + + + bin + Google.Apis.dll + 1.58.0 + + + + + + Providers\SmtpOAuthProviders\GoogleMail + + Resources.zip + + + + + + + \ No newline at end of file diff --git a/DNN Platform/Providers/SmtpOAuthProviders/GoogleMailAuthProvider/Properties/AssemblyInfo.cs b/DNN Platform/Providers/SmtpOAuthProviders/GoogleMailAuthProvider/Properties/AssemblyInfo.cs new file mode 100644 index 00000000000..b3d54de5eb7 --- /dev/null +++ b/DNN Platform/Providers/SmtpOAuthProviders/GoogleMailAuthProvider/Properties/AssemblyInfo.cs @@ -0,0 +1,12 @@ +// +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the MIT License. See LICENSE file in the project root for full license information. +// +#region Usings +using System; +using System.Reflection; +#endregion + +[assembly: AssemblyTitle("DotNetNuke")] + +[assembly: CLSCompliant(true)] diff --git a/DNN Platform/Providers/SmtpOAuthProviders/GoogleMailAuthProvider/Provider.build b/DNN Platform/Providers/SmtpOAuthProviders/GoogleMailAuthProvider/Provider.build new file mode 100644 index 00000000000..bb3c115539e --- /dev/null +++ b/DNN Platform/Providers/SmtpOAuthProviders/GoogleMailAuthProvider/Provider.build @@ -0,0 +1,29 @@ + + + $(MSBuildProjectDirectory)\..\..\..\.. + + + + zip + GoogleMailAuthProvider + DNNCE_GoogleMailAuthProvider + + $(WebsiteInstallPath)\Provider + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/DNN Platform/Providers/SmtpOAuthProviders/GoogleMailAuthProvider/Services/ServiceRouteMapper.cs b/DNN Platform/Providers/SmtpOAuthProviders/GoogleMailAuthProvider/Services/ServiceRouteMapper.cs new file mode 100644 index 00000000000..0af4da068a7 --- /dev/null +++ b/DNN Platform/Providers/SmtpOAuthProviders/GoogleMailAuthProvider/Services/ServiceRouteMapper.cs @@ -0,0 +1,21 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + +namespace Dnn.GoogleMailAuthProvider.Services; + +using DotNetNuke.Web.Api; + +/// +public class ServiceRouteMapper : IServiceRouteMapper +{ + /// + public void RegisterRoutes(IMapRoute routeManager) + { + routeManager.MapHttpRoute( + "GoogleMailAuth", + "default", + "{controller}/{action}", + new[] { "Dnn.GoogleMailAuthProvider.Services" }); + } +} diff --git a/DNN Platform/Providers/SmtpOAuthProviders/GoogleMailAuthProvider/Services/ServicesController.cs b/DNN Platform/Providers/SmtpOAuthProviders/GoogleMailAuthProvider/Services/ServicesController.cs new file mode 100644 index 00000000000..ae6230e9cc7 --- /dev/null +++ b/DNN Platform/Providers/SmtpOAuthProviders/GoogleMailAuthProvider/Services/ServicesController.cs @@ -0,0 +1,13 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + +namespace Dnn.GoogleMailAuthProvider.Services; + +using DotNetNuke.Web.Api; + +/// +[DnnAuthorize] +public class ServicesController : DnnApiController +{ +} diff --git a/DNN Platform/Providers/SmtpOAuthProviders/GoogleMailAuthProvider/app.config b/DNN Platform/Providers/SmtpOAuthProviders/GoogleMailAuthProvider/app.config new file mode 100644 index 00000000000..eac412fe488 --- /dev/null +++ b/DNN Platform/Providers/SmtpOAuthProviders/GoogleMailAuthProvider/app.config @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/DNN Platform/Providers/SmtpOAuthProviders/GoogleMailAuthProvider/license.txt b/DNN Platform/Providers/SmtpOAuthProviders/GoogleMailAuthProvider/license.txt new file mode 100644 index 00000000000..67ea9ae6bb8 --- /dev/null +++ b/DNN Platform/Providers/SmtpOAuthProviders/GoogleMailAuthProvider/license.txt @@ -0,0 +1,20 @@ +
      +

      License

      +

      + Copyright (c) .NET Foundation and Contributors
      + All Rights Reserved +

      +

      + Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated + documentation files (the "Software"), to deal in the Software without restriction, including without limitation + the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and + to permit persons to whom the Software is furnished to do so, subject to the following conditions: +

      +

      + The above copyright notice and this permission notice shall be included in all copies or substantial portions + of the Software. +

      +

      + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +

      +
      \ No newline at end of file diff --git a/DNN Platform/Providers/SmtpOAuthProviders/GoogleMailAuthProvider/packages.config b/DNN Platform/Providers/SmtpOAuthProviders/GoogleMailAuthProvider/packages.config new file mode 100644 index 00000000000..ba7b7fecd38 --- /dev/null +++ b/DNN Platform/Providers/SmtpOAuthProviders/GoogleMailAuthProvider/packages.config @@ -0,0 +1,17 @@ + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/DNN Platform/Providers/SmtpOAuthProviders/GoogleMailAuthProvider/releaseNotes.txt b/DNN Platform/Providers/SmtpOAuthProviders/GoogleMailAuthProvider/releaseNotes.txt new file mode 100644 index 00000000000..e1e23a4bfc6 --- /dev/null +++ b/DNN Platform/Providers/SmtpOAuthProviders/GoogleMailAuthProvider/releaseNotes.txt @@ -0,0 +1 @@ +There are no release notes for this version. diff --git a/DNN Platform/Skins/Xcillion/DotNetNuke.Skins.Xcillion.csproj b/DNN Platform/Skins/Xcillion/DotNetNuke.Skins.Xcillion.csproj index 84d3110736c..f7d3299a8d4 100644 --- a/DNN Platform/Skins/Xcillion/DotNetNuke.Skins.Xcillion.csproj +++ b/DNN Platform/Skins/Xcillion/DotNetNuke.Skins.Xcillion.csproj @@ -39,7 +39,8 @@ 1 bin\DotNetNuke.Skins.Xcillion.XML 1591 - 7 + latest + true pdbonly @@ -50,13 +51,13 @@ 4 bin\DotNetNuke.Skins.Xcillion.XML 1591 - 7 + latest + true - ..\..\..\packages\Newtonsoft.Json.13.0.2\lib\net45\Newtonsoft.Json.dll - True + ..\..\..\packages\Newtonsoft.Json.13.0.3\lib\net45\Newtonsoft.Json.dll diff --git a/DNN Platform/Skins/Xcillion/packages.config b/DNN Platform/Skins/Xcillion/packages.config index 2ba764a647c..63ff0247e18 100644 --- a/DNN Platform/Skins/Xcillion/packages.config +++ b/DNN Platform/Skins/Xcillion/packages.config @@ -3,6 +3,6 @@ - + \ No newline at end of file diff --git a/DNN Platform/Syndication/DotNetNuke.Syndication.csproj b/DNN Platform/Syndication/DotNetNuke.Syndication.csproj index 953957ef143..919d480168f 100644 --- a/DNN Platform/Syndication/DotNetNuke.Syndication.csproj +++ b/DNN Platform/Syndication/DotNetNuke.Syndication.csproj @@ -41,7 +41,7 @@ AllRules.ruleset bin\DotNetNuke.Services.Syndication.xml 1591 - 7 + latest true @@ -55,7 +55,7 @@ 1591 bin\DotNetNuke.Services.Syndication.xml true - 7 + latest true diff --git a/DNN Platform/Tests/App.config b/DNN Platform/Tests/App.config index 95eedde44a2..3757a08e605 100644 --- a/DNN Platform/Tests/App.config +++ b/DNN Platform/Tests/App.config @@ -114,7 +114,7 @@ - + + \ No newline at end of file diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Mail/Properties/AssemblyInfo.cs b/DNN Platform/Tests/DotNetNuke.Tests.Mail/Properties/AssemblyInfo.cs new file mode 100644 index 00000000000..68ceb90a115 --- /dev/null +++ b/DNN Platform/Tests/DotNetNuke.Tests.Mail/Properties/AssemblyInfo.cs @@ -0,0 +1,40 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("DotNetNuke.Test.Mail")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("DotNetNuke Corporation")] +[assembly: AssemblyProduct("DotNetNuke.Test.Mail")] +[assembly: AssemblyCopyright("DotNetNuke is copyright 2002-2022 by DotNetNuke Corporation. All Rights Reserved.")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("b5980c04-f368-4b30-8ec9-5c2b17a581f2")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Mail/SmtpOAuthControllerTest.cs b/DNN Platform/Tests/DotNetNuke.Tests.Mail/SmtpOAuthControllerTest.cs new file mode 100644 index 00000000000..f5892e84c83 --- /dev/null +++ b/DNN Platform/Tests/DotNetNuke.Tests.Mail/SmtpOAuthControllerTest.cs @@ -0,0 +1,52 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information + +namespace DotNetNuke.Tests.Mail +{ + using Dnn.ExchangeOnlineAuthProvider.Components; + using Dnn.GoogleMailAuthProvider.Components; + using DotNetNuke.Abstractions.Application; + using DotNetNuke.Abstractions.Portals; + using DotNetNuke.Services.Mail.OAuth; + using Moq; + using NUnit.Framework; + + [TestFixture] + public class SmtpOAuthControllerTest + { + [Test] + public void Google_OAuth_Provider_Should_Exists() + { + var provider = CreateSmtpOAuthController().GetOAuthProvider("GoogleMail"); + + Assert.NotNull(provider); + } + + [Test] + public void Exchange_OAuth_Provider_Should_Exists() + { + var provider = CreateSmtpOAuthController().GetOAuthProvider("ExchangeOnline"); + + Assert.NotNull(provider); + } + + [Test] + public void NonExistent_OAuth_Provider_Should_Be_Null() + { + var provider = CreateSmtpOAuthController().GetOAuthProvider("AnotherProvider"); + + Assert.Null(provider); + } + + private static SmtpOAuthController CreateSmtpOAuthController() + { + return new SmtpOAuthController( + new ISmtpOAuthProvider[] + { + new GoogleMailOAuthProvider(Mock.Of(), Mock.Of()), + new ExchangeOnlineOAuthProvider(Mock.Of(), Mock.Of()), + }); + } + } +} diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Mail/packages.config b/DNN Platform/Tests/DotNetNuke.Tests.Mail/packages.config new file mode 100644 index 00000000000..a6d4160b423 --- /dev/null +++ b/DNN Platform/Tests/DotNetNuke.Tests.Mail/packages.config @@ -0,0 +1,12 @@ + + + + + + + + + + + + \ No newline at end of file diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Modules/DotNetNuke.Tests.Modules.csproj b/DNN Platform/Tests/DotNetNuke.Tests.Modules/DotNetNuke.Tests.Modules.csproj index f7c0a0a20ba..7088b1b2010 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Modules/DotNetNuke.Tests.Modules.csproj +++ b/DNN Platform/Tests/DotNetNuke.Tests.Modules/DotNetNuke.Tests.Modules.csproj @@ -50,7 +50,8 @@ 4 AllRules.ruleset 1591, 0618,SA0001 - 7 + latest + true pdbonly @@ -61,7 +62,8 @@ 4 AllRules.ruleset 1591, 0618,SA0001 - 7 + latest + true diff --git a/DNN Platform/Tests/DotNetNuke.Tests.SourceGenerators/DnnDeprecatedGeneratorTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.SourceGenerators/DnnDeprecatedGeneratorTests.cs new file mode 100644 index 00000000000..afbf6d998d2 --- /dev/null +++ b/DNN Platform/Tests/DotNetNuke.Tests.SourceGenerators/DnnDeprecatedGeneratorTests.cs @@ -0,0 +1,332 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information +namespace DotNetNuke.Tests.SourceGenerators; + +[TestFixture] +public class DnnDeprecatedGeneratorTests +{ + [Test] + public async Task NotDeprecatedClass_DoesNotGenerateAnything() + { + await Verify(""" +namespace Example.Test; + +using DotNetNuke.Internal.SourceGenerators; + +public partial class PagesController +{ +} + +"""); + } + + [Test] + public async Task DeprecatedNonPartialClass_ReportsAnErrorDiagnostic() + { + await Verify(""" +namespace Example.Test; + +using DotNetNuke.Internal.SourceGenerators; + +[DnnDeprecated(10, 0, 0, "Please resolve IPagesController via dependency injection.")] +public class PagesController +{ +} + +"""); + } + + [Test] + public async Task DeprecatedPartialClass_AddsPartialWithObsoleteAttribute() + { + await Verify(""" +namespace Example.Test; + +using DotNetNuke.Internal.SourceGenerators; + +[DnnDeprecated(10, 0, 0, "Please resolve IPagesController via dependency injection.")] +public partial class PagesController +{ +} + +"""); + } + + [Test] + public async Task DeprecatedGenericPartialClass_AddsPartialWithObsoleteAttribute() + { + await Verify(""" +namespace Example.Test; + +using DotNetNuke.Internal.SourceGenerators; + +[DnnDeprecated(10, 0, 0, "Please resolve IPagesController via dependency injection.")] +public partial class PagesController +{ +} + +"""); + } + + [Test] + public async Task DeprecatedNestedGenericPartialClass_AddsPartialWithObsoleteAttribute() + { + await Verify(""" +namespace Example.Test; + +using DotNetNuke.Internal.SourceGenerators; + +public partial class PagesController +{ + [DnnDeprecated(10, 0, 0, "Please use outer class.")] + public partial class Inner + { + } +} + +"""); + } + + [Test] + public async Task DeprecatedPartialInterface_AddsPartialWithObsoleteAttribute() + { + await Verify(""" +namespace Example.Test; + +using DotNetNuke.Internal.SourceGenerators; + +[DnnDeprecated(10, 0, 0, "Please use the other IPagesController.")] +public partial interface IPagesController +{ +} + +"""); + } + + [Test] + public async Task DeprecatedPartialGenericInterface_AddsPartialWithObsoleteAttribute() + { + await Verify(""" +namespace Example.Test; + +using DotNetNuke.Internal.SourceGenerators; + +[DnnDeprecated(10, 0, 0, "Please use the other IPagesController.")] +public partial interface IPagesController +{ +} + +"""); + } + + [Test] + public async Task DeprecatedPartialStruct_AddsPartialWithObsoleteAttribute() + { + await Verify(""" +namespace Example.Test; + +using DotNetNuke.Internal.SourceGenerators; + +[DnnDeprecated(10, 0, 0, "Please use PageInfo.")] +public partial struct Page +{ +} + +"""); + } + + [Test] + public async Task DeprecatedPartialRecord_AddsPartialWithObsoleteAttribute() + { + await Verify(""" +namespace Example.Test; + +using DotNetNuke.Internal.SourceGenerators; + +[DnnDeprecated(10, 0, 0, "Please use PageInfo.")] +public partial record Page +{ +} + +"""); + } + + [Test] + public async Task DeprecatedNestedPartialRecord_AddsPartialWithObsoleteAttribute() + { + await Verify(""" +namespace Example.Test; + +using DotNetNuke.Internal.SourceGenerators; + +public partial class Page +{ + [DnnDeprecated(9, 1, 2, "Please use InnerPageInfo.")] + public partial record InnerPage + { + } +} + +"""); + } + + [Test] + public async Task DeprecatedWithSpecialCharacters_AddsPartialWithObsoleteAttribute() + { + await Verify("""" +namespace Example.Test; + +using DotNetNuke.Internal.SourceGenerators; + +[DnnDeprecated(9, 1, 2, @"Use PageMaker.MakePage(""PageType0"")")] +public partial class Page +{ + [DnnDeprecated(9, 2, 2, "Use PageMaker.MakePage(\"\n\tPageType1\t\n\")")] + public static partial void MakePage() + { + } + + [DnnDeprecated(9, 2, 2, """ Use PageMaker.MakePage("PageType2") """)] + public static partial void MakePage2() + { + } +} + +""""); + } + + [Test] + public async Task DeprecatedMethods_AddsPartialWithObsoleteAttribute() + { + await Verify(""" +namespace Example.Test; + +using System; +using System.Collections.Generic; +using DotNetNuke.Internal.SourceGenerators; + +internal partial class Page +{ + internal partial static class StaticWrapper + { + [DnnDeprecated(8, 4, 4, "Use overload taking IServiceProvider.")] + public static partial void DoAThing(ref IEnumerable i) + where T : class, new() + { + return; + } + + [DnnDeprecated(9, 4, 4, "Use overload taking IApplicationStatusInfo.")] + public static partial int?[] GetTheseThings(int? a = null, int b = -1) + { + return new[] { a, b, }; + } + } + + internal partial class Wrapper + { + [DnnDeprecated(8, 4, 4, "Use overload taking IApplicationStatusInfo.")] + internal partial (decimal, Int32) GetThemBoth(decimal x, bool addOne = true) + { + var theInt = addOne ? 1 : 2; + return (x + theInt, theInt); + } + + [DnnDeprecated(9, 4, 4, "Use overload taking IServiceProvider.")] + public static partial System.Text.StringBuilder CombineThings(string y, out String z) + { + z = nameof(CombineThings); + return new StringBuilder(y + z); + } + } +} + +"""); + } + + [Test] + public async Task DeprecatedMethodWithParamsParameter_AddsPartialWithObsoleteAttribute() + { + await Verify(""" +namespace Example.Test; + +using DotNetNuke.Internal.SourceGenerators; + +partial class Page +{ + [DnnDeprecated(9, 9, 1, "Use overload taking IEnumerable.")] + partial void WithParams(params int[] numbers) + { + } +} + +"""); + } + + [Test] + public async Task DeprecatedMethodWithOptionalParameters_AddsPartialWithObsoleteAttribute() + { + await Verify(""" +namespace Example.Test; + +using System.Collections; +using System.IO; +using System.Runtime.InteropServices; + +using DotNetNuke.Internal.SourceGenerators; + +partial class Page +{ + [DnnDeprecated(7, 0, 0, "No replacement", RemovalVersion = 11)] + public static partial ArrayList GetFileList( + DirectoryInfo currentDirectory, + [Optional, DefaultParameterValue("")] // ERROR: Optional parameters aren't supported in C# + string strExtensions, + [Optional, DefaultParameterValue(true)] // ERROR: Optional parameters aren't supported in C# + bool noneSpecified) + { + return null; + } +} + +"""); + } + + [Test] + public async Task DeprecatedExtensionMethod_AddsPartialWithObsoleteAttribute() + { + await Verify(""" +namespace Example.Test; + +using DotNetNuke.Internal.SourceGenerators; + +partial class Page +{ + [DnnDeprecated(9, 9, 1, "Use overload taking IEnumerable.")] + partial void AnExtension(this int[] numbers, string another) + { + } +} + +"""); + } + + private static async Task Verify(string source) + { + var references = + AppDomain.CurrentDomain.GetAssemblies() + .Where(a => !a.IsDynamic && !string.IsNullOrEmpty(a.Location)) + .Select(a => MetadataReference.CreateFromFile(a.Location)) + .Append(MetadataReference.CreateFromFile(typeof(DnnDeprecatedGenerator).Assembly.Location)); + var compilation = CSharpCompilation.Create( + "AnAssemblyName", + new[] { CSharpSyntaxTree.ParseText(source), }, + references); + var driver = + CSharpGeneratorDriver + .Create(new DnnDeprecatedGenerator()) + .RunGenerators(compilation); + await Verifier.Verify(driver).UseDirectory("Snapshots"); + } +} diff --git a/DNN Platform/Tests/DotNetNuke.Tests.SourceGenerators/DotNetNuke.Tests.SourceGenerators.csproj b/DNN Platform/Tests/DotNetNuke.Tests.SourceGenerators/DotNetNuke.Tests.SourceGenerators.csproj new file mode 100644 index 00000000000..34ef0bd522d --- /dev/null +++ b/DNN Platform/Tests/DotNetNuke.Tests.SourceGenerators/DotNetNuke.Tests.SourceGenerators.csproj @@ -0,0 +1,48 @@ + + + + net6.0 + enable + enable + + false + + latest + true + 1591,SA0001 + + + + + + + + + + + + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + + + + + + + + + + diff --git a/DNN Platform/Tests/DotNetNuke.Tests.SourceGenerators/Init.cs b/DNN Platform/Tests/DotNetNuke.Tests.SourceGenerators/Init.cs new file mode 100644 index 00000000000..ad3d357c285 --- /dev/null +++ b/DNN Platform/Tests/DotNetNuke.Tests.SourceGenerators/Init.cs @@ -0,0 +1,10 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information +using System.Runtime.CompilerServices; + +public static class Init +{ + [ModuleInitializer] + public static void Initialize() => VerifySourceGenerators.Initialize(); +} diff --git a/DNN Platform/Tests/DotNetNuke.Tests.SourceGenerators/Snapshots/DnnDeprecatedGeneratorTests.DeprecatedExtensionMethod_AddsPartialWithObsoleteAttribute#DnnDeprecatedAttribute.g.verified.cs b/DNN Platform/Tests/DotNetNuke.Tests.SourceGenerators/Snapshots/DnnDeprecatedGeneratorTests.DeprecatedExtensionMethod_AddsPartialWithObsoleteAttribute#DnnDeprecatedAttribute.g.verified.cs new file mode 100644 index 00000000000..474172b29dd --- /dev/null +++ b/DNN Platform/Tests/DotNetNuke.Tests.SourceGenerators/Snapshots/DnnDeprecatedGeneratorTests.DeprecatedExtensionMethod_AddsPartialWithObsoleteAttribute#DnnDeprecatedAttribute.g.verified.cs @@ -0,0 +1,39 @@ +//HintName: DnnDeprecatedAttribute.g.cs +namespace DotNetNuke.Internal.SourceGenerators; + +using System; +using System.Diagnostics; + +/// Marks a type or member as deprecated. +[Conditional("DNN_SOURCE_GENERATOR")] +internal class DnnDeprecatedAttribute : Attribute +{ + /// Initializes a new instance of the class. + /// The major version in which the type or member was deprecated. + /// The minor version in which the type or member was deprecated. + /// The patch version in which the type or member was deprecated. + /// The suggested replacement or alternative. + public DnnDeprecatedAttribute(int majorVersion, int minorVersion, int patchVersion, string replacement) + { + this.MajorVersion = majorVersion; + this.MinorVersion = minorVersion; + this.PatchVersion = patchVersion; + this.Replacement = replacement; + this.RemovalVersion = majorVersion + 2; + } + + /// Gets the major version in which the type or member was deprecated. + public int MajorVersion { get; } + + /// Gets the minor version in which the type or member was deprecated. + public int MinorVersion { get; } + + /// Gets the patch version in which the type or member was deprecated. + public int PatchVersion { get; } + + /// Gets the suggested replacement or alternative. + public string Replacement { get; } + + /// Gets or sets the major version in which the type or member will be removed. + public int RemovalVersion { get; set; } +} \ No newline at end of file diff --git a/DNN Platform/Tests/DotNetNuke.Tests.SourceGenerators/Snapshots/DnnDeprecatedGeneratorTests.DeprecatedExtensionMethod_AddsPartialWithObsoleteAttribute#Example.Test.Page.AnExtension(int[],string).verified.cs b/DNN Platform/Tests/DotNetNuke.Tests.SourceGenerators/Snapshots/DnnDeprecatedGeneratorTests.DeprecatedExtensionMethod_AddsPartialWithObsoleteAttribute#Example.Test.Page.AnExtension(int[],string).verified.cs new file mode 100644 index 00000000000..05a69eb3f3a --- /dev/null +++ b/DNN Platform/Tests/DotNetNuke.Tests.SourceGenerators/Snapshots/DnnDeprecatedGeneratorTests.DeprecatedExtensionMethod_AddsPartialWithObsoleteAttribute#Example.Test.Page.AnExtension(int[],string).verified.cs @@ -0,0 +1,12 @@ +//HintName: Example.Test.Page.AnExtension(int[],string).cs +// +namespace Example.Test; + +partial class Page +{ + [global::System.Obsolete(@"Deprecated in DotNetNuke 9.9.1. Use overload taking IEnumerable. Scheduled for removal in v11.0.0.")] + partial void AnExtension( + this int[] numbers, + string another); +} + diff --git a/DNN Platform/Tests/DotNetNuke.Tests.SourceGenerators/Snapshots/DnnDeprecatedGeneratorTests.DeprecatedGenericPartialClass_AddsPartialWithObsoleteAttribute#DnnDeprecatedAttribute.g.verified.cs b/DNN Platform/Tests/DotNetNuke.Tests.SourceGenerators/Snapshots/DnnDeprecatedGeneratorTests.DeprecatedGenericPartialClass_AddsPartialWithObsoleteAttribute#DnnDeprecatedAttribute.g.verified.cs new file mode 100644 index 00000000000..474172b29dd --- /dev/null +++ b/DNN Platform/Tests/DotNetNuke.Tests.SourceGenerators/Snapshots/DnnDeprecatedGeneratorTests.DeprecatedGenericPartialClass_AddsPartialWithObsoleteAttribute#DnnDeprecatedAttribute.g.verified.cs @@ -0,0 +1,39 @@ +//HintName: DnnDeprecatedAttribute.g.cs +namespace DotNetNuke.Internal.SourceGenerators; + +using System; +using System.Diagnostics; + +/// Marks a type or member as deprecated. +[Conditional("DNN_SOURCE_GENERATOR")] +internal class DnnDeprecatedAttribute : Attribute +{ + /// Initializes a new instance of the class. + /// The major version in which the type or member was deprecated. + /// The minor version in which the type or member was deprecated. + /// The patch version in which the type or member was deprecated. + /// The suggested replacement or alternative. + public DnnDeprecatedAttribute(int majorVersion, int minorVersion, int patchVersion, string replacement) + { + this.MajorVersion = majorVersion; + this.MinorVersion = minorVersion; + this.PatchVersion = patchVersion; + this.Replacement = replacement; + this.RemovalVersion = majorVersion + 2; + } + + /// Gets the major version in which the type or member was deprecated. + public int MajorVersion { get; } + + /// Gets the minor version in which the type or member was deprecated. + public int MinorVersion { get; } + + /// Gets the patch version in which the type or member was deprecated. + public int PatchVersion { get; } + + /// Gets the suggested replacement or alternative. + public string Replacement { get; } + + /// Gets or sets the major version in which the type or member will be removed. + public int RemovalVersion { get; set; } +} \ No newline at end of file diff --git a/DNN Platform/Tests/DotNetNuke.Tests.SourceGenerators/Snapshots/DnnDeprecatedGeneratorTests.DeprecatedGenericPartialClass_AddsPartialWithObsoleteAttribute#Example.Test.PagesController`2.verified.cs b/DNN Platform/Tests/DotNetNuke.Tests.SourceGenerators/Snapshots/DnnDeprecatedGeneratorTests.DeprecatedGenericPartialClass_AddsPartialWithObsoleteAttribute#Example.Test.PagesController`2.verified.cs new file mode 100644 index 00000000000..07c0732e60f --- /dev/null +++ b/DNN Platform/Tests/DotNetNuke.Tests.SourceGenerators/Snapshots/DnnDeprecatedGeneratorTests.DeprecatedGenericPartialClass_AddsPartialWithObsoleteAttribute#Example.Test.PagesController`2.verified.cs @@ -0,0 +1,9 @@ +//HintName: Example.Test.PagesController`2.cs +// +namespace Example.Test; + +[global::System.Obsolete(@"Deprecated in DotNetNuke 10.0.0. Please resolve IPagesController via dependency injection. Scheduled for removal in v12.0.0.")] +partial class PagesController +{ +} + diff --git a/DNN Platform/Tests/DotNetNuke.Tests.SourceGenerators/Snapshots/DnnDeprecatedGeneratorTests.DeprecatedMethodWithOptionalParameters_AddsPartialWithObsoleteAttribute#DnnDeprecatedAttribute.g.verified.cs b/DNN Platform/Tests/DotNetNuke.Tests.SourceGenerators/Snapshots/DnnDeprecatedGeneratorTests.DeprecatedMethodWithOptionalParameters_AddsPartialWithObsoleteAttribute#DnnDeprecatedAttribute.g.verified.cs new file mode 100644 index 00000000000..474172b29dd --- /dev/null +++ b/DNN Platform/Tests/DotNetNuke.Tests.SourceGenerators/Snapshots/DnnDeprecatedGeneratorTests.DeprecatedMethodWithOptionalParameters_AddsPartialWithObsoleteAttribute#DnnDeprecatedAttribute.g.verified.cs @@ -0,0 +1,39 @@ +//HintName: DnnDeprecatedAttribute.g.cs +namespace DotNetNuke.Internal.SourceGenerators; + +using System; +using System.Diagnostics; + +/// Marks a type or member as deprecated. +[Conditional("DNN_SOURCE_GENERATOR")] +internal class DnnDeprecatedAttribute : Attribute +{ + /// Initializes a new instance of the class. + /// The major version in which the type or member was deprecated. + /// The minor version in which the type or member was deprecated. + /// The patch version in which the type or member was deprecated. + /// The suggested replacement or alternative. + public DnnDeprecatedAttribute(int majorVersion, int minorVersion, int patchVersion, string replacement) + { + this.MajorVersion = majorVersion; + this.MinorVersion = minorVersion; + this.PatchVersion = patchVersion; + this.Replacement = replacement; + this.RemovalVersion = majorVersion + 2; + } + + /// Gets the major version in which the type or member was deprecated. + public int MajorVersion { get; } + + /// Gets the minor version in which the type or member was deprecated. + public int MinorVersion { get; } + + /// Gets the patch version in which the type or member was deprecated. + public int PatchVersion { get; } + + /// Gets the suggested replacement or alternative. + public string Replacement { get; } + + /// Gets or sets the major version in which the type or member will be removed. + public int RemovalVersion { get; set; } +} \ No newline at end of file diff --git a/DNN Platform/Tests/DotNetNuke.Tests.SourceGenerators/Snapshots/DnnDeprecatedGeneratorTests.DeprecatedMethodWithOptionalParameters_AddsPartialWithObsoleteAttribute#Example.Test.Page.GetFileList(DirectoryInfo,string,bool).verified.cs b/DNN Platform/Tests/DotNetNuke.Tests.SourceGenerators/Snapshots/DnnDeprecatedGeneratorTests.DeprecatedMethodWithOptionalParameters_AddsPartialWithObsoleteAttribute#Example.Test.Page.GetFileList(DirectoryInfo,string,bool).verified.cs new file mode 100644 index 00000000000..93d54a15c81 --- /dev/null +++ b/DNN Platform/Tests/DotNetNuke.Tests.SourceGenerators/Snapshots/DnnDeprecatedGeneratorTests.DeprecatedMethodWithOptionalParameters_AddsPartialWithObsoleteAttribute#Example.Test.Page.GetFileList(DirectoryInfo,string,bool).verified.cs @@ -0,0 +1,13 @@ +//HintName: Example.Test.Page.GetFileList(DirectoryInfo,string,bool).cs +// +namespace Example.Test; + +partial class Page +{ + [global::System.Obsolete(@"Deprecated in DotNetNuke 7.0.0. No replacement. Scheduled for removal in v11.0.0.")] + public static partial global::System.Collections.ArrayList GetFileList( + global::System.IO.DirectoryInfo currentDirectory, + string strExtensions = @"", + bool noneSpecified = true); +} + diff --git a/DNN Platform/Tests/DotNetNuke.Tests.SourceGenerators/Snapshots/DnnDeprecatedGeneratorTests.DeprecatedMethodWithParamsParameter_AddsPartialWithObsoleteAttribute#DnnDeprecatedAttribute.g.verified.cs b/DNN Platform/Tests/DotNetNuke.Tests.SourceGenerators/Snapshots/DnnDeprecatedGeneratorTests.DeprecatedMethodWithParamsParameter_AddsPartialWithObsoleteAttribute#DnnDeprecatedAttribute.g.verified.cs new file mode 100644 index 00000000000..474172b29dd --- /dev/null +++ b/DNN Platform/Tests/DotNetNuke.Tests.SourceGenerators/Snapshots/DnnDeprecatedGeneratorTests.DeprecatedMethodWithParamsParameter_AddsPartialWithObsoleteAttribute#DnnDeprecatedAttribute.g.verified.cs @@ -0,0 +1,39 @@ +//HintName: DnnDeprecatedAttribute.g.cs +namespace DotNetNuke.Internal.SourceGenerators; + +using System; +using System.Diagnostics; + +/// Marks a type or member as deprecated. +[Conditional("DNN_SOURCE_GENERATOR")] +internal class DnnDeprecatedAttribute : Attribute +{ + /// Initializes a new instance of the class. + /// The major version in which the type or member was deprecated. + /// The minor version in which the type or member was deprecated. + /// The patch version in which the type or member was deprecated. + /// The suggested replacement or alternative. + public DnnDeprecatedAttribute(int majorVersion, int minorVersion, int patchVersion, string replacement) + { + this.MajorVersion = majorVersion; + this.MinorVersion = minorVersion; + this.PatchVersion = patchVersion; + this.Replacement = replacement; + this.RemovalVersion = majorVersion + 2; + } + + /// Gets the major version in which the type or member was deprecated. + public int MajorVersion { get; } + + /// Gets the minor version in which the type or member was deprecated. + public int MinorVersion { get; } + + /// Gets the patch version in which the type or member was deprecated. + public int PatchVersion { get; } + + /// Gets the suggested replacement or alternative. + public string Replacement { get; } + + /// Gets or sets the major version in which the type or member will be removed. + public int RemovalVersion { get; set; } +} \ No newline at end of file diff --git a/DNN Platform/Tests/DotNetNuke.Tests.SourceGenerators/Snapshots/DnnDeprecatedGeneratorTests.DeprecatedMethodWithParamsParameter_AddsPartialWithObsoleteAttribute#Example.Test.Page.WithParams(int[]).verified.cs b/DNN Platform/Tests/DotNetNuke.Tests.SourceGenerators/Snapshots/DnnDeprecatedGeneratorTests.DeprecatedMethodWithParamsParameter_AddsPartialWithObsoleteAttribute#Example.Test.Page.WithParams(int[]).verified.cs new file mode 100644 index 00000000000..817ef0de132 --- /dev/null +++ b/DNN Platform/Tests/DotNetNuke.Tests.SourceGenerators/Snapshots/DnnDeprecatedGeneratorTests.DeprecatedMethodWithParamsParameter_AddsPartialWithObsoleteAttribute#Example.Test.Page.WithParams(int[]).verified.cs @@ -0,0 +1,11 @@ +//HintName: Example.Test.Page.WithParams(int[]).cs +// +namespace Example.Test; + +partial class Page +{ + [global::System.Obsolete(@"Deprecated in DotNetNuke 9.9.1. Use overload taking IEnumerable. Scheduled for removal in v11.0.0.")] + partial void WithParams( + params int[] numbers); +} + diff --git a/DNN Platform/Tests/DotNetNuke.Tests.SourceGenerators/Snapshots/DnnDeprecatedGeneratorTests.DeprecatedMethods_AddsPartialWithObsoleteAttribute#DnnDeprecatedAttribute.g.verified.cs b/DNN Platform/Tests/DotNetNuke.Tests.SourceGenerators/Snapshots/DnnDeprecatedGeneratorTests.DeprecatedMethods_AddsPartialWithObsoleteAttribute#DnnDeprecatedAttribute.g.verified.cs new file mode 100644 index 00000000000..474172b29dd --- /dev/null +++ b/DNN Platform/Tests/DotNetNuke.Tests.SourceGenerators/Snapshots/DnnDeprecatedGeneratorTests.DeprecatedMethods_AddsPartialWithObsoleteAttribute#DnnDeprecatedAttribute.g.verified.cs @@ -0,0 +1,39 @@ +//HintName: DnnDeprecatedAttribute.g.cs +namespace DotNetNuke.Internal.SourceGenerators; + +using System; +using System.Diagnostics; + +/// Marks a type or member as deprecated. +[Conditional("DNN_SOURCE_GENERATOR")] +internal class DnnDeprecatedAttribute : Attribute +{ + /// Initializes a new instance of the class. + /// The major version in which the type or member was deprecated. + /// The minor version in which the type or member was deprecated. + /// The patch version in which the type or member was deprecated. + /// The suggested replacement or alternative. + public DnnDeprecatedAttribute(int majorVersion, int minorVersion, int patchVersion, string replacement) + { + this.MajorVersion = majorVersion; + this.MinorVersion = minorVersion; + this.PatchVersion = patchVersion; + this.Replacement = replacement; + this.RemovalVersion = majorVersion + 2; + } + + /// Gets the major version in which the type or member was deprecated. + public int MajorVersion { get; } + + /// Gets the minor version in which the type or member was deprecated. + public int MinorVersion { get; } + + /// Gets the patch version in which the type or member was deprecated. + public int PatchVersion { get; } + + /// Gets the suggested replacement or alternative. + public string Replacement { get; } + + /// Gets or sets the major version in which the type or member will be removed. + public int RemovalVersion { get; set; } +} \ No newline at end of file diff --git a/DNN Platform/Tests/DotNetNuke.Tests.SourceGenerators/Snapshots/DnnDeprecatedGeneratorTests.DeprecatedMethods_AddsPartialWithObsoleteAttribute#Example.Test.Page.StaticWrapper.DoAThing`1(ref IEnumerable__T__).verified.cs b/DNN Platform/Tests/DotNetNuke.Tests.SourceGenerators/Snapshots/DnnDeprecatedGeneratorTests.DeprecatedMethods_AddsPartialWithObsoleteAttribute#Example.Test.Page.StaticWrapper.DoAThing`1(ref IEnumerable__T__).verified.cs new file mode 100644 index 00000000000..59eab312c7f --- /dev/null +++ b/DNN Platform/Tests/DotNetNuke.Tests.SourceGenerators/Snapshots/DnnDeprecatedGeneratorTests.DeprecatedMethods_AddsPartialWithObsoleteAttribute#Example.Test.Page.StaticWrapper.DoAThing`1(ref IEnumerable__T__).verified.cs @@ -0,0 +1,15 @@ +//HintName: Example.Test.Page.StaticWrapper.DoAThing`1(ref IEnumerable__T__).cs +// +namespace Example.Test; + +partial class Page +{ + partial class StaticWrapper + { + [global::System.Obsolete(@"Deprecated in DotNetNuke 8.4.4. Use overload taking IServiceProvider. Scheduled for removal in v10.0.0.")] + public static partial void DoAThing( + ref global::System.Collections.Generic.IEnumerable i) + where T : class,new(); + } +} + diff --git a/DNN Platform/Tests/DotNetNuke.Tests.SourceGenerators/Snapshots/DnnDeprecatedGeneratorTests.DeprecatedMethods_AddsPartialWithObsoleteAttribute#Example.Test.Page.StaticWrapper.GetTheseThings(int_NULLABLE_,int).verified.cs b/DNN Platform/Tests/DotNetNuke.Tests.SourceGenerators/Snapshots/DnnDeprecatedGeneratorTests.DeprecatedMethods_AddsPartialWithObsoleteAttribute#Example.Test.Page.StaticWrapper.GetTheseThings(int_NULLABLE_,int).verified.cs new file mode 100644 index 00000000000..7c26e2ad7e0 --- /dev/null +++ b/DNN Platform/Tests/DotNetNuke.Tests.SourceGenerators/Snapshots/DnnDeprecatedGeneratorTests.DeprecatedMethods_AddsPartialWithObsoleteAttribute#Example.Test.Page.StaticWrapper.GetTheseThings(int_NULLABLE_,int).verified.cs @@ -0,0 +1,15 @@ +//HintName: Example.Test.Page.StaticWrapper.GetTheseThings(int_NULLABLE_,int).cs +// +namespace Example.Test; + +partial class Page +{ + partial class StaticWrapper + { + [global::System.Obsolete(@"Deprecated in DotNetNuke 9.4.4. Use overload taking IApplicationStatusInfo. Scheduled for removal in v11.0.0.")] + public static partial int?[] GetTheseThings( + int? a = null, + int b = -1); + } +} + diff --git a/DNN Platform/Tests/DotNetNuke.Tests.SourceGenerators/Snapshots/DnnDeprecatedGeneratorTests.DeprecatedMethods_AddsPartialWithObsoleteAttribute#Example.Test.Page.Wrapper`1.CombineThings(string,out string).verified.cs b/DNN Platform/Tests/DotNetNuke.Tests.SourceGenerators/Snapshots/DnnDeprecatedGeneratorTests.DeprecatedMethods_AddsPartialWithObsoleteAttribute#Example.Test.Page.Wrapper`1.CombineThings(string,out string).verified.cs new file mode 100644 index 00000000000..bff4ef589e5 --- /dev/null +++ b/DNN Platform/Tests/DotNetNuke.Tests.SourceGenerators/Snapshots/DnnDeprecatedGeneratorTests.DeprecatedMethods_AddsPartialWithObsoleteAttribute#Example.Test.Page.Wrapper`1.CombineThings(string,out string).verified.cs @@ -0,0 +1,15 @@ +//HintName: Example.Test.Page.Wrapper`1.CombineThings(string,out string).cs +// +namespace Example.Test; + +partial class Page +{ + partial class Wrapper + { + [global::System.Obsolete(@"Deprecated in DotNetNuke 9.4.4. Use overload taking IServiceProvider. Scheduled for removal in v11.0.0.")] + public static partial global::System.Text.StringBuilder CombineThings( + string y, + out string z); + } +} + diff --git a/DNN Platform/Tests/DotNetNuke.Tests.SourceGenerators/Snapshots/DnnDeprecatedGeneratorTests.DeprecatedMethods_AddsPartialWithObsoleteAttribute#Example.Test.Page.Wrapper`1.GetThemBoth(decimal,bool).verified.cs b/DNN Platform/Tests/DotNetNuke.Tests.SourceGenerators/Snapshots/DnnDeprecatedGeneratorTests.DeprecatedMethods_AddsPartialWithObsoleteAttribute#Example.Test.Page.Wrapper`1.GetThemBoth(decimal,bool).verified.cs new file mode 100644 index 00000000000..89396115508 --- /dev/null +++ b/DNN Platform/Tests/DotNetNuke.Tests.SourceGenerators/Snapshots/DnnDeprecatedGeneratorTests.DeprecatedMethods_AddsPartialWithObsoleteAttribute#Example.Test.Page.Wrapper`1.GetThemBoth(decimal,bool).verified.cs @@ -0,0 +1,15 @@ +//HintName: Example.Test.Page.Wrapper`1.GetThemBoth(decimal,bool).cs +// +namespace Example.Test; + +partial class Page +{ + partial class Wrapper + { + [global::System.Obsolete(@"Deprecated in DotNetNuke 8.4.4. Use overload taking IApplicationStatusInfo. Scheduled for removal in v10.0.0.")] + internal partial (decimal, int) GetThemBoth( + decimal x, + bool addOne = true); + } +} + diff --git a/DNN Platform/Tests/DotNetNuke.Tests.SourceGenerators/Snapshots/DnnDeprecatedGeneratorTests.DeprecatedNestedGenericPartialClass_AddsPartialWithObsoleteAttribute#DnnDeprecatedAttribute.g.verified.cs b/DNN Platform/Tests/DotNetNuke.Tests.SourceGenerators/Snapshots/DnnDeprecatedGeneratorTests.DeprecatedNestedGenericPartialClass_AddsPartialWithObsoleteAttribute#DnnDeprecatedAttribute.g.verified.cs new file mode 100644 index 00000000000..c8549271f3e --- /dev/null +++ b/DNN Platform/Tests/DotNetNuke.Tests.SourceGenerators/Snapshots/DnnDeprecatedGeneratorTests.DeprecatedNestedGenericPartialClass_AddsPartialWithObsoleteAttribute#DnnDeprecatedAttribute.g.verified.cs @@ -0,0 +1,39 @@ +//HintName: DnnDeprecatedAttribute.g.cs +namespace DotNetNuke.Internal.SourceGenerators; + +using System; +using System.Diagnostics; + +/// Marks a type or member as deprecated. +[Conditional("DNN_SOURCE_GENERATOR")] +internal class DnnDeprecatedAttribute : Attribute +{ + /// Initializes a new instance of the class. + /// The major version in which the type or member was deprecated. + /// The minor version in which the type or member was deprecated. + /// The patch version in which the type or member was deprecated. + /// The suggested replacement or alternative. + public DnnDeprecatedAttribute(int majorVersion, int minorVersion, int patchVersion, string replacement) + { + this.MajorVersion = majorVersion; + this.MinorVersion = minorVersion; + this.PatchVersion = patchVersion; + this.Replacement = replacement; + this.RemovalVersion = majorVersion + 2; + } + + /// Gets the major version in which the type or member was deprecated. + public int MajorVersion { get; } + + /// Gets the minor version in which the type or member was deprecated. + public int MinorVersion { get; } + + /// Gets the patch version in which the type or member was deprecated. + public int PatchVersion { get; } + + /// Gets the suggested replacement or alternative. + public string Replacement { get; } + + /// Gets or sets the major version in which the type or member will be removed. + public int RemovalVersion { get; set; } +} \ No newline at end of file diff --git a/DNN Platform/Tests/DotNetNuke.Tests.SourceGenerators/Snapshots/DnnDeprecatedGeneratorTests.DeprecatedNestedGenericPartialClass_AddsPartialWithObsoleteAttribute#Example.Test.PagesController`2.Inner`3.verified.cs b/DNN Platform/Tests/DotNetNuke.Tests.SourceGenerators/Snapshots/DnnDeprecatedGeneratorTests.DeprecatedNestedGenericPartialClass_AddsPartialWithObsoleteAttribute#Example.Test.PagesController`2.Inner`3.verified.cs new file mode 100644 index 00000000000..2de0d823ff6 --- /dev/null +++ b/DNN Platform/Tests/DotNetNuke.Tests.SourceGenerators/Snapshots/DnnDeprecatedGeneratorTests.DeprecatedNestedGenericPartialClass_AddsPartialWithObsoleteAttribute#Example.Test.PagesController`2.Inner`3.verified.cs @@ -0,0 +1,12 @@ +//HintName: Example.Test.PagesController`2.Inner`3.cs +// +namespace Example.Test; + +partial class PagesController +{ + [global::System.Obsolete(@"Deprecated in DotNetNuke 10.0.0. Please use outer class. Scheduled for removal in v12.0.0.")] + partial class Inner + { + } +} + diff --git a/DNN Platform/Tests/DotNetNuke.Tests.SourceGenerators/Snapshots/DnnDeprecatedGeneratorTests.DeprecatedNestedPartialRecord_AddsPartialWithObsoleteAttribute#DnnDeprecatedAttribute.g.verified.cs b/DNN Platform/Tests/DotNetNuke.Tests.SourceGenerators/Snapshots/DnnDeprecatedGeneratorTests.DeprecatedNestedPartialRecord_AddsPartialWithObsoleteAttribute#DnnDeprecatedAttribute.g.verified.cs new file mode 100644 index 00000000000..c8549271f3e --- /dev/null +++ b/DNN Platform/Tests/DotNetNuke.Tests.SourceGenerators/Snapshots/DnnDeprecatedGeneratorTests.DeprecatedNestedPartialRecord_AddsPartialWithObsoleteAttribute#DnnDeprecatedAttribute.g.verified.cs @@ -0,0 +1,39 @@ +//HintName: DnnDeprecatedAttribute.g.cs +namespace DotNetNuke.Internal.SourceGenerators; + +using System; +using System.Diagnostics; + +/// Marks a type or member as deprecated. +[Conditional("DNN_SOURCE_GENERATOR")] +internal class DnnDeprecatedAttribute : Attribute +{ + /// Initializes a new instance of the class. + /// The major version in which the type or member was deprecated. + /// The minor version in which the type or member was deprecated. + /// The patch version in which the type or member was deprecated. + /// The suggested replacement or alternative. + public DnnDeprecatedAttribute(int majorVersion, int minorVersion, int patchVersion, string replacement) + { + this.MajorVersion = majorVersion; + this.MinorVersion = minorVersion; + this.PatchVersion = patchVersion; + this.Replacement = replacement; + this.RemovalVersion = majorVersion + 2; + } + + /// Gets the major version in which the type or member was deprecated. + public int MajorVersion { get; } + + /// Gets the minor version in which the type or member was deprecated. + public int MinorVersion { get; } + + /// Gets the patch version in which the type or member was deprecated. + public int PatchVersion { get; } + + /// Gets the suggested replacement or alternative. + public string Replacement { get; } + + /// Gets or sets the major version in which the type or member will be removed. + public int RemovalVersion { get; set; } +} \ No newline at end of file diff --git a/DNN Platform/Tests/DotNetNuke.Tests.SourceGenerators/Snapshots/DnnDeprecatedGeneratorTests.DeprecatedNestedPartialRecord_AddsPartialWithObsoleteAttribute#Example.Test.Page.InnerPage.verified.cs b/DNN Platform/Tests/DotNetNuke.Tests.SourceGenerators/Snapshots/DnnDeprecatedGeneratorTests.DeprecatedNestedPartialRecord_AddsPartialWithObsoleteAttribute#Example.Test.Page.InnerPage.verified.cs new file mode 100644 index 00000000000..f9b96035fcf --- /dev/null +++ b/DNN Platform/Tests/DotNetNuke.Tests.SourceGenerators/Snapshots/DnnDeprecatedGeneratorTests.DeprecatedNestedPartialRecord_AddsPartialWithObsoleteAttribute#Example.Test.Page.InnerPage.verified.cs @@ -0,0 +1,12 @@ +//HintName: Example.Test.Page.InnerPage.cs +// +namespace Example.Test; + +partial class Page +{ + [global::System.Obsolete(@"Deprecated in DotNetNuke 9.1.2. Please use InnerPageInfo. Scheduled for removal in v11.0.0.")] + partial record InnerPage + { + } +} + diff --git a/DNN Platform/Tests/DotNetNuke.Tests.SourceGenerators/Snapshots/DnnDeprecatedGeneratorTests.DeprecatedNonPartialClass_ReportsAnErrorDiagnostic#DnnDeprecatedAttribute.g.verified.cs b/DNN Platform/Tests/DotNetNuke.Tests.SourceGenerators/Snapshots/DnnDeprecatedGeneratorTests.DeprecatedNonPartialClass_ReportsAnErrorDiagnostic#DnnDeprecatedAttribute.g.verified.cs new file mode 100644 index 00000000000..c8549271f3e --- /dev/null +++ b/DNN Platform/Tests/DotNetNuke.Tests.SourceGenerators/Snapshots/DnnDeprecatedGeneratorTests.DeprecatedNonPartialClass_ReportsAnErrorDiagnostic#DnnDeprecatedAttribute.g.verified.cs @@ -0,0 +1,39 @@ +//HintName: DnnDeprecatedAttribute.g.cs +namespace DotNetNuke.Internal.SourceGenerators; + +using System; +using System.Diagnostics; + +/// Marks a type or member as deprecated. +[Conditional("DNN_SOURCE_GENERATOR")] +internal class DnnDeprecatedAttribute : Attribute +{ + /// Initializes a new instance of the class. + /// The major version in which the type or member was deprecated. + /// The minor version in which the type or member was deprecated. + /// The patch version in which the type or member was deprecated. + /// The suggested replacement or alternative. + public DnnDeprecatedAttribute(int majorVersion, int minorVersion, int patchVersion, string replacement) + { + this.MajorVersion = majorVersion; + this.MinorVersion = minorVersion; + this.PatchVersion = patchVersion; + this.Replacement = replacement; + this.RemovalVersion = majorVersion + 2; + } + + /// Gets the major version in which the type or member was deprecated. + public int MajorVersion { get; } + + /// Gets the minor version in which the type or member was deprecated. + public int MinorVersion { get; } + + /// Gets the patch version in which the type or member was deprecated. + public int PatchVersion { get; } + + /// Gets the suggested replacement or alternative. + public string Replacement { get; } + + /// Gets or sets the major version in which the type or member will be removed. + public int RemovalVersion { get; set; } +} \ No newline at end of file diff --git a/DNN Platform/Tests/DotNetNuke.Tests.SourceGenerators/Snapshots/DnnDeprecatedGeneratorTests.DeprecatedNonPartialClass_ReportsAnErrorDiagnostic.verified.txt b/DNN Platform/Tests/DotNetNuke.Tests.SourceGenerators/Snapshots/DnnDeprecatedGeneratorTests.DeprecatedNonPartialClass_ReportsAnErrorDiagnostic.verified.txt new file mode 100644 index 00000000000..cf1b35f014d --- /dev/null +++ b/DNN Platform/Tests/DotNetNuke.Tests.SourceGenerators/Snapshots/DnnDeprecatedGeneratorTests.DeprecatedNonPartialClass_ReportsAnErrorDiagnostic.verified.txt @@ -0,0 +1,16 @@ +{ + Diagnostics: [ + { + Id: DNN1001, + Title: Must be partial, + Severity: Error, + WarningLevel: 0, + Location: : (4,0)-(7,1), + Description: , + HelpLink: , + MessageFormat: The member that the DnnDeprecated attribute is applied to must be partial, + Message: The member that the DnnDeprecated attribute is applied to must be partial, + Category: Usage + } + ] +} \ No newline at end of file diff --git a/DNN Platform/Tests/DotNetNuke.Tests.SourceGenerators/Snapshots/DnnDeprecatedGeneratorTests.DeprecatedPartialClass_AddsPartialWithObsoleteAttribute#DnnDeprecatedAttribute.g.verified.cs b/DNN Platform/Tests/DotNetNuke.Tests.SourceGenerators/Snapshots/DnnDeprecatedGeneratorTests.DeprecatedPartialClass_AddsPartialWithObsoleteAttribute#DnnDeprecatedAttribute.g.verified.cs new file mode 100644 index 00000000000..c8549271f3e --- /dev/null +++ b/DNN Platform/Tests/DotNetNuke.Tests.SourceGenerators/Snapshots/DnnDeprecatedGeneratorTests.DeprecatedPartialClass_AddsPartialWithObsoleteAttribute#DnnDeprecatedAttribute.g.verified.cs @@ -0,0 +1,39 @@ +//HintName: DnnDeprecatedAttribute.g.cs +namespace DotNetNuke.Internal.SourceGenerators; + +using System; +using System.Diagnostics; + +/// Marks a type or member as deprecated. +[Conditional("DNN_SOURCE_GENERATOR")] +internal class DnnDeprecatedAttribute : Attribute +{ + /// Initializes a new instance of the class. + /// The major version in which the type or member was deprecated. + /// The minor version in which the type or member was deprecated. + /// The patch version in which the type or member was deprecated. + /// The suggested replacement or alternative. + public DnnDeprecatedAttribute(int majorVersion, int minorVersion, int patchVersion, string replacement) + { + this.MajorVersion = majorVersion; + this.MinorVersion = minorVersion; + this.PatchVersion = patchVersion; + this.Replacement = replacement; + this.RemovalVersion = majorVersion + 2; + } + + /// Gets the major version in which the type or member was deprecated. + public int MajorVersion { get; } + + /// Gets the minor version in which the type or member was deprecated. + public int MinorVersion { get; } + + /// Gets the patch version in which the type or member was deprecated. + public int PatchVersion { get; } + + /// Gets the suggested replacement or alternative. + public string Replacement { get; } + + /// Gets or sets the major version in which the type or member will be removed. + public int RemovalVersion { get; set; } +} \ No newline at end of file diff --git a/DNN Platform/Tests/DotNetNuke.Tests.SourceGenerators/Snapshots/DnnDeprecatedGeneratorTests.DeprecatedPartialClass_AddsPartialWithObsoleteAttribute#Example.Test.PagesController.verified.cs b/DNN Platform/Tests/DotNetNuke.Tests.SourceGenerators/Snapshots/DnnDeprecatedGeneratorTests.DeprecatedPartialClass_AddsPartialWithObsoleteAttribute#Example.Test.PagesController.verified.cs new file mode 100644 index 00000000000..e82f31d10bf --- /dev/null +++ b/DNN Platform/Tests/DotNetNuke.Tests.SourceGenerators/Snapshots/DnnDeprecatedGeneratorTests.DeprecatedPartialClass_AddsPartialWithObsoleteAttribute#Example.Test.PagesController.verified.cs @@ -0,0 +1,9 @@ +//HintName: Example.Test.PagesController.cs +// +namespace Example.Test; + +[global::System.Obsolete(@"Deprecated in DotNetNuke 10.0.0. Please resolve IPagesController via dependency injection. Scheduled for removal in v12.0.0.")] +partial class PagesController +{ +} + diff --git a/DNN Platform/Tests/DotNetNuke.Tests.SourceGenerators/Snapshots/DnnDeprecatedGeneratorTests.DeprecatedPartialGenericInterface_AddsPartialWithObsoleteAttribute#DnnDeprecatedAttribute.g.verified.cs b/DNN Platform/Tests/DotNetNuke.Tests.SourceGenerators/Snapshots/DnnDeprecatedGeneratorTests.DeprecatedPartialGenericInterface_AddsPartialWithObsoleteAttribute#DnnDeprecatedAttribute.g.verified.cs new file mode 100644 index 00000000000..c8549271f3e --- /dev/null +++ b/DNN Platform/Tests/DotNetNuke.Tests.SourceGenerators/Snapshots/DnnDeprecatedGeneratorTests.DeprecatedPartialGenericInterface_AddsPartialWithObsoleteAttribute#DnnDeprecatedAttribute.g.verified.cs @@ -0,0 +1,39 @@ +//HintName: DnnDeprecatedAttribute.g.cs +namespace DotNetNuke.Internal.SourceGenerators; + +using System; +using System.Diagnostics; + +/// Marks a type or member as deprecated. +[Conditional("DNN_SOURCE_GENERATOR")] +internal class DnnDeprecatedAttribute : Attribute +{ + /// Initializes a new instance of the class. + /// The major version in which the type or member was deprecated. + /// The minor version in which the type or member was deprecated. + /// The patch version in which the type or member was deprecated. + /// The suggested replacement or alternative. + public DnnDeprecatedAttribute(int majorVersion, int minorVersion, int patchVersion, string replacement) + { + this.MajorVersion = majorVersion; + this.MinorVersion = minorVersion; + this.PatchVersion = patchVersion; + this.Replacement = replacement; + this.RemovalVersion = majorVersion + 2; + } + + /// Gets the major version in which the type or member was deprecated. + public int MajorVersion { get; } + + /// Gets the minor version in which the type or member was deprecated. + public int MinorVersion { get; } + + /// Gets the patch version in which the type or member was deprecated. + public int PatchVersion { get; } + + /// Gets the suggested replacement or alternative. + public string Replacement { get; } + + /// Gets or sets the major version in which the type or member will be removed. + public int RemovalVersion { get; set; } +} \ No newline at end of file diff --git a/DNN Platform/Tests/DotNetNuke.Tests.SourceGenerators/Snapshots/DnnDeprecatedGeneratorTests.DeprecatedPartialGenericInterface_AddsPartialWithObsoleteAttribute#Example.Test.IPagesController`1.verified.cs b/DNN Platform/Tests/DotNetNuke.Tests.SourceGenerators/Snapshots/DnnDeprecatedGeneratorTests.DeprecatedPartialGenericInterface_AddsPartialWithObsoleteAttribute#Example.Test.IPagesController`1.verified.cs new file mode 100644 index 00000000000..bd984690c83 --- /dev/null +++ b/DNN Platform/Tests/DotNetNuke.Tests.SourceGenerators/Snapshots/DnnDeprecatedGeneratorTests.DeprecatedPartialGenericInterface_AddsPartialWithObsoleteAttribute#Example.Test.IPagesController`1.verified.cs @@ -0,0 +1,9 @@ +//HintName: Example.Test.IPagesController`1.cs +// +namespace Example.Test; + +[global::System.Obsolete(@"Deprecated in DotNetNuke 10.0.0. Please use the other IPagesController. Scheduled for removal in v12.0.0.")] +partial interface IPagesController +{ +} + diff --git a/DNN Platform/Tests/DotNetNuke.Tests.SourceGenerators/Snapshots/DnnDeprecatedGeneratorTests.DeprecatedPartialInterface_AddsPartialWithObsoleteAttribute#DnnDeprecatedAttribute.g.verified.cs b/DNN Platform/Tests/DotNetNuke.Tests.SourceGenerators/Snapshots/DnnDeprecatedGeneratorTests.DeprecatedPartialInterface_AddsPartialWithObsoleteAttribute#DnnDeprecatedAttribute.g.verified.cs new file mode 100644 index 00000000000..c8549271f3e --- /dev/null +++ b/DNN Platform/Tests/DotNetNuke.Tests.SourceGenerators/Snapshots/DnnDeprecatedGeneratorTests.DeprecatedPartialInterface_AddsPartialWithObsoleteAttribute#DnnDeprecatedAttribute.g.verified.cs @@ -0,0 +1,39 @@ +//HintName: DnnDeprecatedAttribute.g.cs +namespace DotNetNuke.Internal.SourceGenerators; + +using System; +using System.Diagnostics; + +/// Marks a type or member as deprecated. +[Conditional("DNN_SOURCE_GENERATOR")] +internal class DnnDeprecatedAttribute : Attribute +{ + /// Initializes a new instance of the class. + /// The major version in which the type or member was deprecated. + /// The minor version in which the type or member was deprecated. + /// The patch version in which the type or member was deprecated. + /// The suggested replacement or alternative. + public DnnDeprecatedAttribute(int majorVersion, int minorVersion, int patchVersion, string replacement) + { + this.MajorVersion = majorVersion; + this.MinorVersion = minorVersion; + this.PatchVersion = patchVersion; + this.Replacement = replacement; + this.RemovalVersion = majorVersion + 2; + } + + /// Gets the major version in which the type or member was deprecated. + public int MajorVersion { get; } + + /// Gets the minor version in which the type or member was deprecated. + public int MinorVersion { get; } + + /// Gets the patch version in which the type or member was deprecated. + public int PatchVersion { get; } + + /// Gets the suggested replacement or alternative. + public string Replacement { get; } + + /// Gets or sets the major version in which the type or member will be removed. + public int RemovalVersion { get; set; } +} \ No newline at end of file diff --git a/DNN Platform/Tests/DotNetNuke.Tests.SourceGenerators/Snapshots/DnnDeprecatedGeneratorTests.DeprecatedPartialInterface_AddsPartialWithObsoleteAttribute#Example.Test.IPagesController.verified.cs b/DNN Platform/Tests/DotNetNuke.Tests.SourceGenerators/Snapshots/DnnDeprecatedGeneratorTests.DeprecatedPartialInterface_AddsPartialWithObsoleteAttribute#Example.Test.IPagesController.verified.cs new file mode 100644 index 00000000000..8ba93a51b51 --- /dev/null +++ b/DNN Platform/Tests/DotNetNuke.Tests.SourceGenerators/Snapshots/DnnDeprecatedGeneratorTests.DeprecatedPartialInterface_AddsPartialWithObsoleteAttribute#Example.Test.IPagesController.verified.cs @@ -0,0 +1,9 @@ +//HintName: Example.Test.IPagesController.cs +// +namespace Example.Test; + +[global::System.Obsolete(@"Deprecated in DotNetNuke 10.0.0. Please use the other IPagesController. Scheduled for removal in v12.0.0.")] +partial interface IPagesController +{ +} + diff --git a/DNN Platform/Tests/DotNetNuke.Tests.SourceGenerators/Snapshots/DnnDeprecatedGeneratorTests.DeprecatedPartialRecord_AddsPartialWithObsoleteAttribute#DnnDeprecatedAttribute.g.verified.cs b/DNN Platform/Tests/DotNetNuke.Tests.SourceGenerators/Snapshots/DnnDeprecatedGeneratorTests.DeprecatedPartialRecord_AddsPartialWithObsoleteAttribute#DnnDeprecatedAttribute.g.verified.cs new file mode 100644 index 00000000000..c8549271f3e --- /dev/null +++ b/DNN Platform/Tests/DotNetNuke.Tests.SourceGenerators/Snapshots/DnnDeprecatedGeneratorTests.DeprecatedPartialRecord_AddsPartialWithObsoleteAttribute#DnnDeprecatedAttribute.g.verified.cs @@ -0,0 +1,39 @@ +//HintName: DnnDeprecatedAttribute.g.cs +namespace DotNetNuke.Internal.SourceGenerators; + +using System; +using System.Diagnostics; + +/// Marks a type or member as deprecated. +[Conditional("DNN_SOURCE_GENERATOR")] +internal class DnnDeprecatedAttribute : Attribute +{ + /// Initializes a new instance of the class. + /// The major version in which the type or member was deprecated. + /// The minor version in which the type or member was deprecated. + /// The patch version in which the type or member was deprecated. + /// The suggested replacement or alternative. + public DnnDeprecatedAttribute(int majorVersion, int minorVersion, int patchVersion, string replacement) + { + this.MajorVersion = majorVersion; + this.MinorVersion = minorVersion; + this.PatchVersion = patchVersion; + this.Replacement = replacement; + this.RemovalVersion = majorVersion + 2; + } + + /// Gets the major version in which the type or member was deprecated. + public int MajorVersion { get; } + + /// Gets the minor version in which the type or member was deprecated. + public int MinorVersion { get; } + + /// Gets the patch version in which the type or member was deprecated. + public int PatchVersion { get; } + + /// Gets the suggested replacement or alternative. + public string Replacement { get; } + + /// Gets or sets the major version in which the type or member will be removed. + public int RemovalVersion { get; set; } +} \ No newline at end of file diff --git a/DNN Platform/Tests/DotNetNuke.Tests.SourceGenerators/Snapshots/DnnDeprecatedGeneratorTests.DeprecatedPartialRecord_AddsPartialWithObsoleteAttribute#Example.Test.Page.verified.cs b/DNN Platform/Tests/DotNetNuke.Tests.SourceGenerators/Snapshots/DnnDeprecatedGeneratorTests.DeprecatedPartialRecord_AddsPartialWithObsoleteAttribute#Example.Test.Page.verified.cs new file mode 100644 index 00000000000..c498ae0b3f7 --- /dev/null +++ b/DNN Platform/Tests/DotNetNuke.Tests.SourceGenerators/Snapshots/DnnDeprecatedGeneratorTests.DeprecatedPartialRecord_AddsPartialWithObsoleteAttribute#Example.Test.Page.verified.cs @@ -0,0 +1,9 @@ +//HintName: Example.Test.Page.cs +// +namespace Example.Test; + +[global::System.Obsolete(@"Deprecated in DotNetNuke 10.0.0. Please use PageInfo. Scheduled for removal in v12.0.0.")] +partial record Page +{ +} + diff --git a/DNN Platform/Tests/DotNetNuke.Tests.SourceGenerators/Snapshots/DnnDeprecatedGeneratorTests.DeprecatedPartialStruct_AddsPartialWithObsoleteAttribute#DnnDeprecatedAttribute.g.verified.cs b/DNN Platform/Tests/DotNetNuke.Tests.SourceGenerators/Snapshots/DnnDeprecatedGeneratorTests.DeprecatedPartialStruct_AddsPartialWithObsoleteAttribute#DnnDeprecatedAttribute.g.verified.cs new file mode 100644 index 00000000000..c8549271f3e --- /dev/null +++ b/DNN Platform/Tests/DotNetNuke.Tests.SourceGenerators/Snapshots/DnnDeprecatedGeneratorTests.DeprecatedPartialStruct_AddsPartialWithObsoleteAttribute#DnnDeprecatedAttribute.g.verified.cs @@ -0,0 +1,39 @@ +//HintName: DnnDeprecatedAttribute.g.cs +namespace DotNetNuke.Internal.SourceGenerators; + +using System; +using System.Diagnostics; + +/// Marks a type or member as deprecated. +[Conditional("DNN_SOURCE_GENERATOR")] +internal class DnnDeprecatedAttribute : Attribute +{ + /// Initializes a new instance of the class. + /// The major version in which the type or member was deprecated. + /// The minor version in which the type or member was deprecated. + /// The patch version in which the type or member was deprecated. + /// The suggested replacement or alternative. + public DnnDeprecatedAttribute(int majorVersion, int minorVersion, int patchVersion, string replacement) + { + this.MajorVersion = majorVersion; + this.MinorVersion = minorVersion; + this.PatchVersion = patchVersion; + this.Replacement = replacement; + this.RemovalVersion = majorVersion + 2; + } + + /// Gets the major version in which the type or member was deprecated. + public int MajorVersion { get; } + + /// Gets the minor version in which the type or member was deprecated. + public int MinorVersion { get; } + + /// Gets the patch version in which the type or member was deprecated. + public int PatchVersion { get; } + + /// Gets the suggested replacement or alternative. + public string Replacement { get; } + + /// Gets or sets the major version in which the type or member will be removed. + public int RemovalVersion { get; set; } +} \ No newline at end of file diff --git a/DNN Platform/Tests/DotNetNuke.Tests.SourceGenerators/Snapshots/DnnDeprecatedGeneratorTests.DeprecatedPartialStruct_AddsPartialWithObsoleteAttribute#Example.Test.Page.verified.cs b/DNN Platform/Tests/DotNetNuke.Tests.SourceGenerators/Snapshots/DnnDeprecatedGeneratorTests.DeprecatedPartialStruct_AddsPartialWithObsoleteAttribute#Example.Test.Page.verified.cs new file mode 100644 index 00000000000..ae8a1a268e5 --- /dev/null +++ b/DNN Platform/Tests/DotNetNuke.Tests.SourceGenerators/Snapshots/DnnDeprecatedGeneratorTests.DeprecatedPartialStruct_AddsPartialWithObsoleteAttribute#Example.Test.Page.verified.cs @@ -0,0 +1,9 @@ +//HintName: Example.Test.Page.cs +// +namespace Example.Test; + +[global::System.Obsolete(@"Deprecated in DotNetNuke 10.0.0. Please use PageInfo. Scheduled for removal in v12.0.0.")] +partial struct Page +{ +} + diff --git a/DNN Platform/Tests/DotNetNuke.Tests.SourceGenerators/Snapshots/DnnDeprecatedGeneratorTests.DeprecatedWithSpecialCharacters_AddsPartialWithObsoleteAttribute#DnnDeprecatedAttribute.g.verified.cs b/DNN Platform/Tests/DotNetNuke.Tests.SourceGenerators/Snapshots/DnnDeprecatedGeneratorTests.DeprecatedWithSpecialCharacters_AddsPartialWithObsoleteAttribute#DnnDeprecatedAttribute.g.verified.cs new file mode 100644 index 00000000000..c8549271f3e --- /dev/null +++ b/DNN Platform/Tests/DotNetNuke.Tests.SourceGenerators/Snapshots/DnnDeprecatedGeneratorTests.DeprecatedWithSpecialCharacters_AddsPartialWithObsoleteAttribute#DnnDeprecatedAttribute.g.verified.cs @@ -0,0 +1,39 @@ +//HintName: DnnDeprecatedAttribute.g.cs +namespace DotNetNuke.Internal.SourceGenerators; + +using System; +using System.Diagnostics; + +/// Marks a type or member as deprecated. +[Conditional("DNN_SOURCE_GENERATOR")] +internal class DnnDeprecatedAttribute : Attribute +{ + /// Initializes a new instance of the class. + /// The major version in which the type or member was deprecated. + /// The minor version in which the type or member was deprecated. + /// The patch version in which the type or member was deprecated. + /// The suggested replacement or alternative. + public DnnDeprecatedAttribute(int majorVersion, int minorVersion, int patchVersion, string replacement) + { + this.MajorVersion = majorVersion; + this.MinorVersion = minorVersion; + this.PatchVersion = patchVersion; + this.Replacement = replacement; + this.RemovalVersion = majorVersion + 2; + } + + /// Gets the major version in which the type or member was deprecated. + public int MajorVersion { get; } + + /// Gets the minor version in which the type or member was deprecated. + public int MinorVersion { get; } + + /// Gets the patch version in which the type or member was deprecated. + public int PatchVersion { get; } + + /// Gets the suggested replacement or alternative. + public string Replacement { get; } + + /// Gets or sets the major version in which the type or member will be removed. + public int RemovalVersion { get; set; } +} \ No newline at end of file diff --git a/DNN Platform/Tests/DotNetNuke.Tests.SourceGenerators/Snapshots/DnnDeprecatedGeneratorTests.DeprecatedWithSpecialCharacters_AddsPartialWithObsoleteAttribute#Example.Test.Page.MakePage().verified.cs b/DNN Platform/Tests/DotNetNuke.Tests.SourceGenerators/Snapshots/DnnDeprecatedGeneratorTests.DeprecatedWithSpecialCharacters_AddsPartialWithObsoleteAttribute#Example.Test.Page.MakePage().verified.cs new file mode 100644 index 00000000000..2029077c909 --- /dev/null +++ b/DNN Platform/Tests/DotNetNuke.Tests.SourceGenerators/Snapshots/DnnDeprecatedGeneratorTests.DeprecatedWithSpecialCharacters_AddsPartialWithObsoleteAttribute#Example.Test.Page.MakePage().verified.cs @@ -0,0 +1,12 @@ +//HintName: Example.Test.Page.MakePage().cs +// +namespace Example.Test; + +partial class Page +{ + [global::System.Obsolete(@"Deprecated in DotNetNuke 9.2.2. Use PageMaker.MakePage("" + PageType1 +""). Scheduled for removal in v11.0.0.")] + public static partial void MakePage(); +} + diff --git a/DNN Platform/Tests/DotNetNuke.Tests.SourceGenerators/Snapshots/DnnDeprecatedGeneratorTests.DeprecatedWithSpecialCharacters_AddsPartialWithObsoleteAttribute#Example.Test.Page.MakePage2().verified.cs b/DNN Platform/Tests/DotNetNuke.Tests.SourceGenerators/Snapshots/DnnDeprecatedGeneratorTests.DeprecatedWithSpecialCharacters_AddsPartialWithObsoleteAttribute#Example.Test.Page.MakePage2().verified.cs new file mode 100644 index 00000000000..a2357c911e7 --- /dev/null +++ b/DNN Platform/Tests/DotNetNuke.Tests.SourceGenerators/Snapshots/DnnDeprecatedGeneratorTests.DeprecatedWithSpecialCharacters_AddsPartialWithObsoleteAttribute#Example.Test.Page.MakePage2().verified.cs @@ -0,0 +1,10 @@ +//HintName: Example.Test.Page.MakePage2().cs +// +namespace Example.Test; + +partial class Page +{ + [global::System.Obsolete(@"Deprecated in DotNetNuke 9.2.2. Use PageMaker.MakePage(""PageType2"") . Scheduled for removal in v11.0.0.")] + public static partial void MakePage2(); +} + diff --git a/DNN Platform/Tests/DotNetNuke.Tests.SourceGenerators/Snapshots/DnnDeprecatedGeneratorTests.DeprecatedWithSpecialCharacters_AddsPartialWithObsoleteAttribute#Example.Test.Page.verified.cs b/DNN Platform/Tests/DotNetNuke.Tests.SourceGenerators/Snapshots/DnnDeprecatedGeneratorTests.DeprecatedWithSpecialCharacters_AddsPartialWithObsoleteAttribute#Example.Test.Page.verified.cs new file mode 100644 index 00000000000..ec626b38321 --- /dev/null +++ b/DNN Platform/Tests/DotNetNuke.Tests.SourceGenerators/Snapshots/DnnDeprecatedGeneratorTests.DeprecatedWithSpecialCharacters_AddsPartialWithObsoleteAttribute#Example.Test.Page.verified.cs @@ -0,0 +1,9 @@ +//HintName: Example.Test.Page.cs +// +namespace Example.Test; + +[global::System.Obsolete(@"Deprecated in DotNetNuke 9.1.2. Use PageMaker.MakePage(""PageType0""). Scheduled for removal in v11.0.0.")] +partial class Page +{ +} + diff --git a/DNN Platform/Tests/DotNetNuke.Tests.SourceGenerators/Snapshots/DnnDeprecatedGeneratorTests.NotDeprecatedClass_DoesNotGenerateAnything#DnnDeprecatedAttribute.g.verified.cs b/DNN Platform/Tests/DotNetNuke.Tests.SourceGenerators/Snapshots/DnnDeprecatedGeneratorTests.NotDeprecatedClass_DoesNotGenerateAnything#DnnDeprecatedAttribute.g.verified.cs new file mode 100644 index 00000000000..c8549271f3e --- /dev/null +++ b/DNN Platform/Tests/DotNetNuke.Tests.SourceGenerators/Snapshots/DnnDeprecatedGeneratorTests.NotDeprecatedClass_DoesNotGenerateAnything#DnnDeprecatedAttribute.g.verified.cs @@ -0,0 +1,39 @@ +//HintName: DnnDeprecatedAttribute.g.cs +namespace DotNetNuke.Internal.SourceGenerators; + +using System; +using System.Diagnostics; + +/// Marks a type or member as deprecated. +[Conditional("DNN_SOURCE_GENERATOR")] +internal class DnnDeprecatedAttribute : Attribute +{ + /// Initializes a new instance of the class. + /// The major version in which the type or member was deprecated. + /// The minor version in which the type or member was deprecated. + /// The patch version in which the type or member was deprecated. + /// The suggested replacement or alternative. + public DnnDeprecatedAttribute(int majorVersion, int minorVersion, int patchVersion, string replacement) + { + this.MajorVersion = majorVersion; + this.MinorVersion = minorVersion; + this.PatchVersion = patchVersion; + this.Replacement = replacement; + this.RemovalVersion = majorVersion + 2; + } + + /// Gets the major version in which the type or member was deprecated. + public int MajorVersion { get; } + + /// Gets the minor version in which the type or member was deprecated. + public int MinorVersion { get; } + + /// Gets the patch version in which the type or member was deprecated. + public int PatchVersion { get; } + + /// Gets the suggested replacement or alternative. + public string Replacement { get; } + + /// Gets or sets the major version in which the type or member will be removed. + public int RemovalVersion { get; set; } +} \ No newline at end of file diff --git a/DNN Platform/Tests/DotNetNuke.Tests.UI/DotNetNuke.Tests.UI.csproj b/DNN Platform/Tests/DotNetNuke.Tests.UI/DotNetNuke.Tests.UI.csproj index 93b2115e01c..5aa649162a1 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.UI/DotNetNuke.Tests.UI.csproj +++ b/DNN Platform/Tests/DotNetNuke.Tests.UI/DotNetNuke.Tests.UI.csproj @@ -50,7 +50,8 @@ 4 AllRules.ruleset 1591,SA0001 - 7 + latest + true pdbonly @@ -61,7 +62,8 @@ 4 AllRules.ruleset 1591,SA0001 - 7 + latest + true diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Urls/DotNetNuke.Tests.Urls.csproj b/DNN Platform/Tests/DotNetNuke.Tests.Urls/DotNetNuke.Tests.Urls.csproj index 55ceb0985bb..0e7ef072fdb 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Urls/DotNetNuke.Tests.Urls.csproj +++ b/DNN Platform/Tests/DotNetNuke.Tests.Urls/DotNetNuke.Tests.Urls.csproj @@ -27,7 +27,8 @@ prompt 4 SA0001 - 7 + latest + true pdbonly @@ -37,7 +38,8 @@ prompt 4 SA0001 - 7 + latest + true diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Utilities/DotNetNuke.Tests.Utilities.csproj b/DNN Platform/Tests/DotNetNuke.Tests.Utilities/DotNetNuke.Tests.Utilities.csproj index ba708ed660e..41c136137c8 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Utilities/DotNetNuke.Tests.Utilities.csproj +++ b/DNN Platform/Tests/DotNetNuke.Tests.Utilities/DotNetNuke.Tests.Utilities.csproj @@ -46,23 +46,27 @@ full false bin\ + bin\DotNetNuke.Tests.Utilities.XML DEBUG;TRACE prompt 4 AllRules.ruleset 1591 - 7 + latest + true pdbonly true bin\ + bin\DotNetNuke.Tests.Utilities.XML TRACE prompt 4 AllRules.ruleset 1591 - 7 + latest + true @@ -132,6 +136,10 @@ + + {5FE5D021-9C8D-47A6-BD34-F328BA3E709C} + DotNetNuke.Internal.SourceGenerators + {6928a9b1-f88a-4581-a132-d3eb38669bb0} DotNetNuke.Abstractions diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Utilities/ExceptionAssert.cs b/DNN Platform/Tests/DotNetNuke.Tests.Utilities/ExceptionAssert.cs index 82e5b6c31ea..be0535871fa 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Utilities/ExceptionAssert.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Utilities/ExceptionAssert.cs @@ -5,12 +5,14 @@ namespace DotNetNuke.Tests.Utilities { using System; - using System.Reflection; - + using System.Reflection; + + using DotNetNuke.Internal.SourceGenerators; + using NUnit.Framework; - [Obsolete("Use Assert.Exception or ExpectedExceptionAttribute. Scheduled removal in v11.0.0.")] - public static class ExceptionAssert + [DnnDeprecated(7, 0, 0, "Use Assert.Exception or ExpectedExceptionAttribute", RemovalVersion = 11)] + public static partial class ExceptionAssert { // public static void Throws(Action act) where TException : Exception // { diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Web.Mvc/DotNetNuke.Tests.Web.Mvc.csproj b/DNN Platform/Tests/DotNetNuke.Tests.Web.Mvc/DotNetNuke.Tests.Web.Mvc.csproj index 7818451b1d9..453bbb8c1ed 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Web.Mvc/DotNetNuke.Tests.Web.Mvc.csproj +++ b/DNN Platform/Tests/DotNetNuke.Tests.Web.Mvc/DotNetNuke.Tests.Web.Mvc.csproj @@ -28,7 +28,8 @@ prompt 4 SA0001 - 7 + latest + true pdbonly @@ -38,7 +39,8 @@ prompt 4 SA0001 - 7 + latest + true @@ -58,8 +60,7 @@ ..\..\..\packages\Moq.4.18.4\lib\net462\Moq.dll - ..\..\..\packages\Newtonsoft.Json.13.0.2\lib\net45\Newtonsoft.Json.dll - True + ..\..\..\packages\Newtonsoft.Json.13.0.3\lib\net45\Newtonsoft.Json.dll ..\..\..\packages\NUnit.3.13.3\lib\net45\nunit.framework.dll diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Web.Mvc/packages.config b/DNN Platform/Tests/DotNetNuke.Tests.Web.Mvc/packages.config index 109279530b1..10ac4c45a84 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Web.Mvc/packages.config +++ b/DNN Platform/Tests/DotNetNuke.Tests.Web.Mvc/packages.config @@ -8,7 +8,7 @@ - + diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Web/DotNetNuke.Tests.Web.csproj b/DNN Platform/Tests/DotNetNuke.Tests.Web/DotNetNuke.Tests.Web.csproj index 2e09510e649..e90b3ccc383 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Web/DotNetNuke.Tests.Web.csproj +++ b/DNN Platform/Tests/DotNetNuke.Tests.Web/DotNetNuke.Tests.Web.csproj @@ -28,7 +28,8 @@ prompt 4 618,SA0001 - 7 + latest + true pdbonly @@ -38,7 +39,8 @@ prompt 4 618,SA0001 - 7 + latest + true @@ -58,8 +60,7 @@ ..\..\..\packages\Moq.4.18.4\lib\net462\Moq.dll - ..\..\..\packages\Newtonsoft.Json.13.0.2\lib\net45\Newtonsoft.Json.dll - True + ..\..\..\packages\Newtonsoft.Json.13.0.3\lib\net45\Newtonsoft.Json.dll ..\..\..\packages\NUnit.3.13.3\lib\net45\nunit.framework.dll diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Web/packages.config b/DNN Platform/Tests/DotNetNuke.Tests.Web/packages.config index 9e501fa0571..2e464281e7e 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Web/packages.config +++ b/DNN Platform/Tests/DotNetNuke.Tests.Web/packages.config @@ -8,7 +8,7 @@ - + diff --git a/DNN Platform/Website/DotNetNuke.Website.csproj b/DNN Platform/Website/DotNetNuke.Website.csproj index 875ffa7b403..7247bf427b5 100644 --- a/DNN Platform/Website/DotNetNuke.Website.csproj +++ b/DNN Platform/Website/DotNetNuke.Website.csproj @@ -55,7 +55,9 @@ 4 bin\DotNetNuke.Website.XML 1591 - 7 + latest + true + CS0618,SA1600,SA1601,SA1602,SA1606,SA1607,SA1611,SA1614 pdbonly @@ -66,7 +68,9 @@ 4 bin\DotNetNuke.Website.XML 1591 - 7 + latest + true + CS0618,SA1600,SA1601,SA1602,SA1606,SA1607,SA1611,SA1614 @@ -89,8 +93,7 @@ True - ..\..\packages\Newtonsoft.Json.13.0.2\lib\net45\Newtonsoft.Json.dll - True + ..\..\packages\Newtonsoft.Json.13.0.3\lib\net45\Newtonsoft.Json.dll False @@ -1250,6 +1253,7 @@ + web.config @@ -2989,7 +2993,6 @@ - @@ -3378,7 +3381,6 @@ - @@ -3411,6 +3413,10 @@ + + {5fe5d021-9c8d-47a6-bd34-f328ba3e709c} + DotNetNuke.Internal.SourceGenerators + {6928a9b1-f88a-4581-a132-d3eb38669bb0} DotNetNuke.Abstractions diff --git a/DNN Platform/Website/Licenses/Effority Ealo (Ms-RL).txt.resources b/DNN Platform/Website/Licenses/Effority Ealo (Ms-RL).txt.resources index 69ef34a15bf..de4a530a888 100644 --- a/DNN Platform/Website/Licenses/Effority Ealo (Ms-RL).txt.resources +++ b/DNN Platform/Website/Licenses/Effority Ealo (Ms-RL).txt.resources @@ -1,4 +1,5 @@ -[Obsolete("Deprecated in 9.4.0, due to limited developer support. Scheduled removal in v10.0.0.")] +[DnnDeprecated(9, 4, 0, "No replacement", RemovalVersion = 10)] +[Obsolete("Deprecated in DotNetNuke 9.4.0. No replacement. Scheduled removal in v10.0.0.")] PROJECT: Effority Ealo diff --git a/DNN Platform/Website/Licenses/WebFormsMVP (MsPL).txt.resources b/DNN Platform/Website/Licenses/WebFormsMVP (MsPL).txt.resources index 9de91548dc6..0a0dc9670ff 100644 --- a/DNN Platform/Website/Licenses/WebFormsMVP (MsPL).txt.resources +++ b/DNN Platform/Website/Licenses/WebFormsMVP (MsPL).txt.resources @@ -1,4 +1,5 @@ -[Obsolete("Deprecated in DNN 9.2.0. Replace WebFormsMvp and DotNetNuke.Web.Mvp with MVC or SPA patterns instead. Scheduled removal in v11.0.0.")] +[DnnDeprecated(9, 2, 0, "Replace WebFormsMvp and DotNetNuke.Web.Mvp with MVC or SPA patterns instead")] +[Obsolete("Deprecated in DotNetNuke 9.2.0. Replace WebFormsMvp and DotNetNuke.Web.Mvp with MVC or SPA patterns instead. Scheduled removal in v11.0.0.")] PROJECT: WebFormsMVP diff --git a/DNN Platform/Website/Providers/DataProviders/SqlDataProvider/09.12.01.SqlDataProvider b/DNN Platform/Website/Providers/DataProviders/SqlDataProvider/09.12.01.SqlDataProvider new file mode 100644 index 00000000000..42377820df7 --- /dev/null +++ b/DNN Platform/Website/Providers/DataProviders/SqlDataProvider/09.12.01.SqlDataProvider @@ -0,0 +1,85 @@ +/************************************************************/ +/***** SqlDataProvider *****/ +/***** *****/ +/***** *****/ +/***** Note: To manually execute this script you must *****/ +/***** perform a search and replace operation *****/ +/***** for {databaseOwner} and {objectQualifier} *****/ +/***** *****/ +/************************************************************/ + +/* Fix GetExtensionUrlProviders #5564 */ +/**************************************/ + +IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'{databaseOwner}[{objectQualifier}GetExtensionUrlProviders]') AND type in (N'P', N'PC')) + DROP PROCEDURE {databaseOwner}[{objectQualifier}GetExtensionUrlProviders] +GO + +CREATE PROCEDURE {databaseOwner}[{objectQualifier}GetExtensionUrlProviders] + @PortalID int +AS + SELECT + p.*, + pc.PortalID + FROM {databaseOwner}{objectQualifier}ExtensionUrlProviderConfiguration pc + RIGHT OUTER JOIN {databaseOwner}{objectQualifier}ExtensionUrlProviders p + ON pc.ExtensionUrlProviderID = p.ExtensionUrlProviderID + WHERE pc.PortalID = @PortalID OR pc.PortalID IS Null + + SELECT ExtensionUrlProviderID, + PortalID, + SettingName, + SettingValue + FROM {databaseOwner}{objectQualifier}ExtensionUrlProviderSetting + WHERE PortalID = @PortalID + + SELECT DISTINCT + P.ExtensionUrlProviderID, + TM.TabID + FROM {databaseOwner}{objectQualifier}DesktopModules DM + INNER JOIN {databaseOwner}{objectQualifier}ModuleDefinitions MD ON DM.DesktopModuleID = MD.DesktopModuleID + INNER JOIN {databaseOwner}{objectQualifier}Modules M ON MD.ModuleDefID = M.ModuleDefID + INNER JOIN {databaseOwner}{objectQualifier}TabModules TM ON M.ModuleID = TM.ModuleID + INNER JOIN {databaseOwner}{objectQualifier}vw_ExtensionUrlProviders P ON DM.DesktopModuleID = P.DesktopModuleId + WHERE (P.PortalID = @PortalID) OR (P.PortalID IS NULL) + + UNION + SELECT + P.ExtensionUrlProviderID, + PT.TabId + FROM {databaseOwner}{objectQualifier}ExtensionUrlProviderTab PT + INNER JOIN {databaseOwner}{objectQualifier}ExtensionUrlProviders P ON P.ExtensionUrlProviderID = PT.ExtensionUrlProviderID + WHERE (PT.IsActive = 1) +GO + + +/* Drop Objects No Longer Needed #5552 */ +IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'{databaseOwner}[{objectQualifier}DeleteSearchWord]') AND type in (N'P', N'PC')) + DROP PROCEDURE {databaseOwner}[{objectQualifier}DeleteSearchWord] +GO +IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'{databaseOwner}[{objectQualifier}ImportDocumentLibraryCategories]') AND type in (N'P', N'PC')) + DROP PROCEDURE {databaseOwner}[{objectQualifier}ImportDocumentLibraryCategories] +GO +IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'{databaseOwner}[{objectQualifier}ImportDocumentLibraryCategoryAssoc]') AND type in (N'P', N'PC')) + DROP PROCEDURE {databaseOwner}[{objectQualifier}ImportDocumentLibraryCategoryAssoc] +GO +IF EXISTS (SELECT * FROM Sys.OBJECTS WHERE (name = N'{objectQualifier}FitsExtendedPropertyPermission') AND TYPE = 'FN') + DROP FUNCTION {databaseOwner}[{objectQualifier}FitsExtendedPropertyPermission] +GO + +/* Fix Scheduler Frequency for Server Monitor #5634 */ + +--Update the retry timelapse to 2 minutes, similar to other standard jobs +UPDATE {databaseOwner}[{objectQualifier}Schedule] +SET RetryTimeLapse = 2 +WHERE TypeFullName = 'DotNetNuke.Services.SystemHealth.WebServerMonitor, DotNetNuke' +AND TimeLapse = 5 +AND RetryTimeLapse = 10 +AND TimeLapseMeasurement = 'm' +AND RetryTimeLapseMeasurement = 'm'; +GO + + +/************************************************************/ +/***** SqlDataProvider *****/ +/************************************************************/ diff --git a/DNN Platform/Website/Resources/Shared/scripts/jquery/jquery-migrate.js b/DNN Platform/Website/Resources/Shared/scripts/jquery/jquery-migrate.js index b3757a9d025..5ef505ed920 100644 --- a/DNN Platform/Website/Resources/Shared/scripts/jquery/jquery-migrate.js +++ b/DNN Platform/Website/Resources/Shared/scripts/jquery/jquery-migrate.js @@ -1,5 +1,5 @@ /*! - * jQuery Migrate - v3.4.0 - 2022-03-24T16:30Z + * jQuery Migrate - v3.4.1 - 2023-02-23T15:31Z * Copyright OpenJS Foundation and other contributors */ ( function( factory ) { @@ -24,7 +24,7 @@ } )( function( jQuery, window ) { "use strict"; -jQuery.migrateVersion = "3.4.0"; +jQuery.migrateVersion = "3.4.1"; // Returns 0 if v1 == v2, -1 if v1 < v2, 1 if v1 > v2 function compareVersions( v1, v2 ) { @@ -91,9 +91,10 @@ jQuery.migrateIsPatchEnabled = function( patchCode ) { return; } - // Need jQuery 3.0.0+ and no older Migrate loaded - if ( !jQuery || !jQueryVersionSince( "3.0.0" ) ) { - window.console.log( "JQMIGRATE: jQuery 3.0.0+ REQUIRED" ); + // Need jQuery 3.x-4.x and no older Migrate loaded + if ( !jQuery || !jQueryVersionSince( "3.0.0" ) || + jQueryVersionSince( "5.0.0" ) ) { + window.console.log( "JQMIGRATE: jQuery 3.x-4.x REQUIRED" ); } if ( jQuery.migrateWarnings ) { window.console.log( "JQMIGRATE: Migrate plugin loaded multiple times" ); @@ -206,9 +207,9 @@ var findProp, rattrHashTest = /\[(\s*[-\w]+\s*)([~|^$*]?=)\s*([-\w#]*?#[-\w#]*)\s*\]/, rattrHashGlob = /\[(\s*[-\w]+\s*)([~|^$*]?=)\s*([-\w#]*?#[-\w#]*)\s*\]/g, - // Support: Android <=4.0 only - // Make sure we trim BOM and NBSP - rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g; + // Require that the "whitespace run" starts from a non-whitespace + // to avoid O(N^2) behavior when the engine would try matching "\s+$" at each space position. + rtrim = /^[\s\uFEFF\xA0]+|([^\s\uFEFF\xA0])[\s\uFEFF\xA0]+$/g; migratePatchFunc( jQuery.fn, "init", function( arg1 ) { var args = Array.prototype.slice.call( arguments ); @@ -300,7 +301,7 @@ if ( jQueryVersionSince( "3.1.1" ) ) { migratePatchAndWarnFunc( jQuery, "trim", function( text ) { return text == null ? "" : - ( text + "" ).replace( rtrim, "" ); + ( text + "" ).replace( rtrim, "$1" ); }, "trim", "jQuery.trim is deprecated; use String.prototype.trim" ); } @@ -419,10 +420,24 @@ var oldRemoveAttr = jQuery.fn.removeAttr, rmatchNonSpace = /\S+/g; migratePatchFunc( jQuery.fn, "removeAttr", function( name ) { - var self = this; + var self = this, + patchNeeded = false; jQuery.each( name.match( rmatchNonSpace ), function( _i, attr ) { if ( jQuery.expr.match.bool.test( attr ) ) { + + // Only warn if at least a single node had the property set to + // something else than `false`. Otherwise, this Migrate patch + // doesn't influence the behavior and there's no need to set or warn. + self.each( function() { + if ( jQuery( this ).prop( attr ) !== false ) { + patchNeeded = true; + return false; + } + } ); + } + + if ( patchNeeded ) { migrateWarn( "removeAttr-bool", "jQuery.fn.removeAttr no longer sets boolean properties: " + attr ); self.prop( attr, false ); @@ -470,7 +485,7 @@ function camelCase( string ) { } ); } -var origFnCss, +var origFnCss, internalCssNumber, internalSwapCall = false, ralphaStart = /^[a-z]/, @@ -552,8 +567,11 @@ if ( jQueryVersionSince( "3.4.0" ) && typeof Proxy !== "undefined" ) { // https://github.com/jquery/jquery/blob/3.6.0/src/css.js#L212-L233 // This way, number values for the CSS properties below won't start triggering // Migrate warnings when jQuery gets updated to >=4.0.0 (gh-438). -if ( jQueryVersionSince( "4.0.0" ) && typeof Proxy !== "undefined" ) { - jQuery.cssNumber = new Proxy( { +if ( jQueryVersionSince( "4.0.0" ) ) { + + // We need to keep this as a local variable as we need it internally + // in a `jQuery.fn.css` patch and this usage shouldn't warn. + internalCssNumber = { animationIterationCount: true, columnCount: true, fillOpacity: true, @@ -574,16 +592,31 @@ if ( jQueryVersionSince( "4.0.0" ) && typeof Proxy !== "undefined" ) { widows: true, zIndex: true, zoom: true - }, { - get: function() { - migrateWarn( "css-number", "jQuery.cssNumber is deprecated" ); - return Reflect.get.apply( this, arguments ); - }, - set: function() { - migrateWarn( "css-number", "jQuery.cssNumber is deprecated" ); - return Reflect.set.apply( this, arguments ); - } - } ); + }; + + if ( typeof Proxy !== "undefined" ) { + jQuery.cssNumber = new Proxy( internalCssNumber, { + get: function() { + migrateWarn( "css-number", "jQuery.cssNumber is deprecated" ); + return Reflect.get.apply( this, arguments ); + }, + set: function() { + migrateWarn( "css-number", "jQuery.cssNumber is deprecated" ); + return Reflect.set.apply( this, arguments ); + } + } ); + } else { + + // Support: IE 9-11+ + // IE doesn't support proxies, but we still want to restore the legacy + // jQuery.cssNumber there. + jQuery.cssNumber = internalCssNumber; + } +} else { + + // Make `internalCssNumber` defined for jQuery <4 as well as it's needed + // in the `jQuery.fn.css` patch below. + internalCssNumber = jQuery.cssNumber; } function isAutoPx( prop ) { @@ -610,7 +643,10 @@ migratePatchFunc( jQuery.fn, "css", function( name, value ) { if ( typeof value === "number" ) { camelName = camelCase( name ); - if ( !isAutoPx( camelName ) && !jQuery.cssNumber[ camelName ] ) { + + // Use `internalCssNumber` to avoid triggering our warnings in this + // internal check. + if ( !isAutoPx( camelName ) && !internalCssNumber[ camelName ] ) { migrateWarn( "css-number", "Number-typed values are deprecated for jQuery.fn.css( \"" + name + "\", value )" ); diff --git a/DNN Platform/Website/Resources/Shared/scripts/jquery/jquery-migrate.min.js b/DNN Platform/Website/Resources/Shared/scripts/jquery/jquery-migrate.min.js index f535eb1993e..29a4939df33 100644 --- a/DNN Platform/Website/Resources/Shared/scripts/jquery/jquery-migrate.min.js +++ b/DNN Platform/Website/Resources/Shared/scripts/jquery/jquery-migrate.min.js @@ -1,2 +1,2 @@ -/*! jQuery Migrate v3.4.0 | (c) OpenJS Foundation and other contributors | jquery.org/license */ -"undefined"==typeof jQuery.migrateMute&&(jQuery.migrateMute=!0),function(t){"use strict";"function"==typeof define&&define.amd?define(["jquery"],function(e){return t(e,window)}):"object"==typeof module&&module.exports?module.exports=t(require("jquery"),window):t(jQuery,window)}(function(s,n){"use strict";function e(e){return 0<=function(e,t){for(var r=/^(\d+)\.(\d+)\.(\d+)/,n=r.exec(e)||[],o=r.exec(t)||[],a=1;a<=3;a++){if(+n[a]>+o[a])return 1;if(+n[a]<+o[a])return-1}return 0}(s.fn.jquery,e)}s.migrateVersion="3.4.0";var t=Object.create(null),o=(s.migrateDisablePatches=function(){for(var e=0;e\x20\t\r\n\f]*)[^>]*)\/>/gi),_=(s.UNSAFE_restoreLegacyHtmlPrefilter=function(){s.migrateEnablePatches("self-closed-tags")},d(s,"htmlPrefilter",function(e){var t,r;return(r=(t=e).replace(O,"<$1>"))!==t&&C(t)!==C(r)&&i("self-closed-tags","HTML tags must be properly nested and closed: "+t),e.replace(O,"<$1>")},"self-closed-tags"),s.migrateDisablePatches("self-closed-tags"),s.fn.offset);return d(s.fn,"offset",function(){var e=this[0];return!e||e.nodeType&&e.getBoundingClientRect?_.apply(this,arguments):(i("offset-valid-elem","jQuery.fn.offset() requires a valid DOM element"),arguments.length?this:void 0)},"offset-valid-elem"),s.ajax&&(H=s.param,d(s,"param",function(e,t){var r=s.ajaxSettings&&s.ajaxSettings.traditional;return void 0===t&&r&&(i("param-ajax-traditional","jQuery.param() no longer uses jQuery.ajaxSettings.traditional"),t=r),H.call(this,e,t)},"param-ajax-traditional")),u(s.fn,"andSelf",s.fn.addBack,"andSelf","jQuery.fn.andSelf() is deprecated and removed, use jQuery.fn.addBack()"),s.Deferred&&(E=s.Deferred,M=[["resolve","done",s.Callbacks("once memory"),s.Callbacks("once memory"),"resolved"],["reject","fail",s.Callbacks("once memory"),s.Callbacks("once memory"),"rejected"],["notify","progress",s.Callbacks("memory"),s.Callbacks("memory")]],d(s,"Deferred",function(e){var a=E(),i=a.promise();function t(){var o=arguments;return s.Deferred(function(n){s.each(M,function(e,t){var r="function"==typeof o[e]&&o[e];a[t[1]](function(){var e=r&&r.apply(this,arguments);e&&"function"==typeof e.promise?e.promise().done(n.resolve).fail(n.reject).progress(n.notify):n[t[0]+"With"](this===i?n.promise():this,r?[e]:arguments)})}),o=null}).promise()}return u(a,"pipe",t,"deferred-pipe","deferred.pipe() is deprecated"),u(i,"pipe",t,"deferred-pipe","deferred.pipe() is deprecated"),e&&e.call(a,a),a},"deferred-pipe"),s.Deferred.exceptionHook=E.exceptionHook),s}); +/*! jQuery Migrate v3.4.1 | (c) OpenJS Foundation and other contributors | jquery.org/license */ +"undefined"==typeof jQuery.migrateMute&&(jQuery.migrateMute=!0),function(t){"use strict";"function"==typeof define&&define.amd?define(["jquery"],function(e){return t(e,window)}):"object"==typeof module&&module.exports?module.exports=t(require("jquery"),window):t(jQuery,window)}(function(s,n){"use strict";function e(e){return 0<=function(e,t){for(var r=/^(\d+)\.(\d+)\.(\d+)/,n=r.exec(e)||[],o=r.exec(t)||[],a=1;a<=3;a++){if(+o[a]<+n[a])return 1;if(+n[a]<+o[a])return-1}return 0}(s.fn.jquery,e)}s.migrateVersion="3.4.1";var t=Object.create(null);s.migrateDisablePatches=function(){for(var e=0;e\x20\t\r\n\f]*)[^>]*)\/>/gi;s.UNSAFE_restoreLegacyHtmlPrefilter=function(){s.migrateEnablePatches("self-closed-tags")},i(s,"htmlPrefilter",function(e){var t,r;return(r=(t=e).replace(F,"<$1>"))!==t&&T(t)!==T(r)&&u("self-closed-tags","HTML tags must be properly nested and closed: "+t),e.replace(F,"<$1>")},"self-closed-tags"),s.migrateDisablePatches("self-closed-tags");var D,W,_,I=s.fn.offset;return i(s.fn,"offset",function(){var e=this[0];return!e||e.nodeType&&e.getBoundingClientRect?I.apply(this,arguments):(u("offset-valid-elem","jQuery.fn.offset() requires a valid DOM element"),arguments.length?this:void 0)},"offset-valid-elem"),s.ajax&&(D=s.param,i(s,"param",function(e,t){var r=s.ajaxSettings&&s.ajaxSettings.traditional;return void 0===t&&r&&(u("param-ajax-traditional","jQuery.param() no longer uses jQuery.ajaxSettings.traditional"),t=r),D.call(this,e,t)},"param-ajax-traditional")),c(s.fn,"andSelf",s.fn.addBack,"andSelf","jQuery.fn.andSelf() is deprecated and removed, use jQuery.fn.addBack()"),s.Deferred&&(W=s.Deferred,_=[["resolve","done",s.Callbacks("once memory"),s.Callbacks("once memory"),"resolved"],["reject","fail",s.Callbacks("once memory"),s.Callbacks("once memory"),"rejected"],["notify","progress",s.Callbacks("memory"),s.Callbacks("memory")]],i(s,"Deferred",function(e){var a=W(),i=a.promise();function t(){var o=arguments;return s.Deferred(function(n){s.each(_,function(e,t){var r="function"==typeof o[e]&&o[e];a[t[1]](function(){var e=r&&r.apply(this,arguments);e&&"function"==typeof e.promise?e.promise().done(n.resolve).fail(n.reject).progress(n.notify):n[t[0]+"With"](this===i?n.promise():this,r?[e]:arguments)})}),o=null}).promise()}return c(a,"pipe",t,"deferred-pipe","deferred.pipe() is deprecated"),c(i,"pipe",t,"deferred-pipe","deferred.pipe() is deprecated"),e&&e.call(a,a),a},"deferred-pipe"),s.Deferred.exceptionHook=W.exceptionHook),s}); diff --git a/DNN Platform/Website/Resources/Shared/scripts/jquery/jquery-vsdoc.js b/DNN Platform/Website/Resources/Shared/scripts/jquery/jquery-vsdoc.js deleted file mode 100644 index d6144db0f9e..00000000000 --- a/DNN Platform/Website/Resources/Shared/scripts/jquery/jquery-vsdoc.js +++ /dev/null @@ -1,6632 +0,0 @@ -/* -* This file has been generated to support Visual Studio IntelliSense. -* You should not use this file at runtime inside the browser--it is only -* intended to be used only for design-time IntelliSense. Please use the -* standard jQuery library for all runtime use. -* -* Comment version: 3.4.1 -*/ - -/*! -* jQuery JavaScript Library v3.4.1 -* http://jquery.com/ -* -* Includes Sizzle.js -* http://sizzlejs.com/ -* -* Copyright 2005, 2012 jQuery Foundation, Inc. and other contributors -* Released under the MIT license -* http://jquery.org/license -* -*/ - -(function (window, undefined) { - var jQuery = function (selector, context) { - /// - /// 1: Accepts a string containing a CSS selector which is then used to match a set of elements. - /// 1.1 - $(selector, context) - /// 1.2 - $(element) - /// 1.3 - $(elementArray) - /// 1.4 - $(object) - /// 1.5 - $(jQuery object) - /// 1.6 - $() - /// 2: Creates DOM elements on the fly from the provided string of raw HTML. - /// 2.1 - $(html, ownerDocument) - /// 2.2 - $(html, attributes) - /// 3: Binds a function to be executed when the DOM has finished loading. - /// 3.1 - $(callback) - /// - /// - /// A string containing a selector expression - /// - /// - /// A DOM Element, Document, or jQuery to use as context - /// - /// - - // The jQuery object is actually just the init constructor 'enhanced' - return new jQuery.fn.init(selector, context, rootjQuery); - }; - jQuery.Animation = function Animation(elem, properties, options) { - - var result, - stopped, - index = 0, - length = animationPrefilters.length, - deferred = jQuery.Deferred().always(function () { - // don't match elem in the :animated selector - delete tick.elem; - }), - tick = function () { - if (stopped) { - return false; - } - var currentTime = fxNow || createFxNow(), - remaining = Math.max(0, animation.startTime + animation.duration - currentTime), - // archaic crash bug won't allow us to use 1 - ( 0.5 || 0 ) (#12497) - temp = remaining / animation.duration || 0, - percent = 1 - temp, - index = 0, - length = animation.tweens.length; - - for (; index < length ; index++) { - animation.tweens[index].run(percent); - } - - deferred.notifyWith(elem, [animation, percent, remaining]); - - if (percent < 1 && length) { - return remaining; - } else { - deferred.resolveWith(elem, [animation]); - return false; - } - }, - animation = deferred.promise({ - elem: elem, - props: jQuery.extend({}, properties), - opts: jQuery.extend(true, { specialEasing: {} }, options), - originalProperties: properties, - originalOptions: options, - startTime: fxNow || createFxNow(), - duration: options.duration, - tweens: [], - createTween: function (prop, end) { - var tween = jQuery.Tween(elem, animation.opts, prop, end, - animation.opts.specialEasing[prop] || animation.opts.easing); - animation.tweens.push(tween); - return tween; - }, - stop: function (gotoEnd) { - var index = 0, - // if we are going to the end, we want to run all the tweens - // otherwise we skip this part - length = gotoEnd ? animation.tweens.length : 0; - if (stopped) { - return this; - } - stopped = true; - for (; index < length ; index++) { - animation.tweens[index].run(1); - } - - // resolve when we played the last frame - // otherwise, reject - if (gotoEnd) { - deferred.resolveWith(elem, [animation, gotoEnd]); - } else { - deferred.rejectWith(elem, [animation, gotoEnd]); - } - return this; - } - }), - props = animation.props; - - propFilter(props, animation.opts.specialEasing); - - for (; index < length ; index++) { - result = animationPrefilters[index].call(animation, elem, props, animation.opts); - if (result) { - return result; - } - } - - createTweens(animation, props); - - if (jQuery.isFunction(animation.opts.start)) { - animation.opts.start.call(elem, animation); - } - - jQuery.fx.timer( - jQuery.extend(tick, { - elem: elem, - anim: animation, - queue: animation.opts.queue - }) - ); - - // attach callbacks from options - return animation.progress(animation.opts.progress) - .done(animation.opts.done, animation.opts.complete) - .fail(animation.opts.fail) - .always(animation.opts.always); - }; - jQuery.Callbacks = function (options) { - /// - /// A multi-purpose callbacks list object that provides a powerful way to manage callback lists. - /// - /// - /// An optional list of space-separated flags that change how the callback list behaves. - /// - /// - - - // Convert options from String-formatted to Object-formatted if needed - // (we check in cache first) - options = typeof options === "string" ? - (optionsCache[options] || createOptions(options)) : - jQuery.extend({}, options); - - var // Last fire value (for non-forgettable lists) - memory, - // Flag to know if list was already fired - fired, - // Flag to know if list is currently firing - firing, - // First callback to fire (used internally by add and fireWith) - firingStart, - // End of the loop when firing - firingLength, - // Index of currently firing callback (modified by remove if needed) - firingIndex, - // Actual callback list - list = [], - // Stack of fire calls for repeatable lists - stack = !options.once && [], - // Fire callbacks - fire = function (data) { - memory = options.memory && data; - fired = true; - firingIndex = firingStart || 0; - firingStart = 0; - firingLength = list.length; - firing = true; - for (; list && firingIndex < firingLength; firingIndex++) { - if (list[firingIndex].apply(data[0], data[1]) === false && options.stopOnFalse) { - memory = false; // To prevent further calls using add - break; - } - } - firing = false; - if (list) { - if (stack) { - if (stack.length) { - fire(stack.shift()); - } - } else if (memory) { - list = []; - } else { - self.disable(); - } - } - }, - // Actual Callbacks object - self = { - // Add a callback or a collection of callbacks to the list - add: function () { - if (list) { - // First, we save the current length - var start = list.length; - (function add(args) { - jQuery.each(args, function (_, arg) { - var type = jQuery.type(arg); - if (type === "function") { - if (!options.unique || !self.has(arg)) { - list.push(arg); - } - } else if (arg && arg.length && type !== "string") { - // Inspect recursively - add(arg); - } - }); - })(arguments); - // Do we need to add the callbacks to the - // current firing batch? - if (firing) { - firingLength = list.length; - // With memory, if we're not firing then - // we should call right away - } else if (memory) { - firingStart = start; - fire(memory); - } - } - return this; - }, - // Remove a callback from the list - remove: function () { - if (list) { - jQuery.each(arguments, function (_, arg) { - var index; - while ((index = jQuery.inArray(arg, list, index)) > -1) { - list.splice(index, 1); - // Handle firing indexes - if (firing) { - if (index <= firingLength) { - firingLength--; - } - if (index <= firingIndex) { - firingIndex--; - } - } - } - }); - } - return this; - }, - // Check if a given callback is in the list. - // If no argument is given, return whether or not list has callbacks attached. - has: function (fn) { - return fn ? jQuery.inArray(fn, list) > -1 : !!(list && list.length); - }, - // Remove all callbacks from the list - empty: function () { - list = []; - firingLength = 0; - return this; - }, - // Have the list do nothing anymore - disable: function () { - list = stack = memory = undefined; - return this; - }, - // Is it disabled? - disabled: function () { - return !list; - }, - // Lock the list in its current state - lock: function () { - stack = undefined; - if (!memory) { - self.disable(); - } - return this; - }, - // Is it locked? - locked: function () { - return !stack; - }, - // Call all callbacks with the given context and arguments - fireWith: function (context, args) { - args = args || []; - args = [context, args.slice ? args.slice() : args]; - if (list && (!fired || stack)) { - if (firing) { - stack.push(args); - } else { - fire(args); - } - } - return this; - }, - // Call all the callbacks with the given arguments - fire: function () { - self.fireWith(this, arguments); - return this; - }, - // To know if the callbacks have already been called at least once - fired: function () { - return !!fired; - } - }; - - return self; - }; - jQuery.Deferred = function (func) { - /// - /// A constructor function that returns a chainable utility object with methods to register multiple callbacks into callback queues, invoke callback queues, and relay the success or failure state of any synchronous or asynchronous function. - /// - /// - /// A function that is called just before the constructor returns. - /// - /// - - var tuples = [ - // action, add listener, listener list, final state - ["resolve", "done", jQuery.Callbacks("once memory"), "resolved"], - ["reject", "fail", jQuery.Callbacks("once memory"), "rejected"], - ["notify", "progress", jQuery.Callbacks("memory")] - ], - state = "pending", - promise = { - state: function () { - return state; - }, - always: function () { - deferred.done(arguments).fail(arguments); - return this; - }, - then: function ( /* fnDone, fnFail, fnProgress */) { - var fns = arguments; - return jQuery.Deferred(function (newDefer) { - jQuery.each(tuples, function (i, tuple) { - var action = tuple[0], - fn = jQuery.isFunction(fns[i]) && fns[i]; - // deferred[ done | fail | progress ] for forwarding actions to newDefer - deferred[tuple[1]](function () { - var returned = fn && fn.apply(this, arguments); - if (returned && jQuery.isFunction(returned.promise)) { - returned.promise() - .done(newDefer.resolve) - .fail(newDefer.reject) - .progress(newDefer.notify); - } else { - newDefer[action + "With"](this === promise ? newDefer.promise() : this, fn ? [returned] : arguments); - } - }); - }); - fns = null; - }).promise(); - }, - // Get a promise for this deferred - // If obj is provided, the promise aspect is added to the object - promise: function (obj) { - return obj != null ? jQuery.extend(obj, promise) : promise; - } - }, - deferred = {}; - - // Keep pipe for back-compat - promise.pipe = promise.then; - - // Add list-specific methods - jQuery.each(tuples, function (i, tuple) { - var list = tuple[2], - stateString = tuple[3]; - - // promise[ done | fail | progress ] = list.add - promise[tuple[1]] = list.add; - - // Handle state - if (stateString) { - list.add(function () { - // state = [ resolved | rejected ] - state = stateString; - - // [ reject_list | resolve_list ].disable; progress_list.lock - }, tuples[i ^ 1][2].disable, tuples[2][2].lock); - } - - // deferred[ resolve | reject | notify ] - deferred[tuple[0]] = function () { - deferred[tuple[0] + "With"](this === deferred ? promise : this, arguments); - return this; - }; - deferred[tuple[0] + "With"] = list.fireWith; - }); - - // Make the deferred a promise - promise.promise(deferred); - - // Call given func if any - if (func) { - func.call(deferred, deferred); - } - - // All done! - return deferred; - }; - jQuery.Event = function (src, props) { - - // Allow instantiation without the 'new' keyword - if (!(this instanceof jQuery.Event)) { - return new jQuery.Event(src, props); - } - - // Event object - if (src && src.type) { - this.originalEvent = src; - this.type = src.type; - - // Events bubbling up the document may have been marked as prevented - // by a handler lower down the tree; reflect the correct value. - this.isDefaultPrevented = (src.defaultPrevented || - src.getPreventDefault && src.getPreventDefault()) ? returnTrue : returnFalse; - - // Event type - } else { - this.type = src; - } - - // Put explicitly provided properties onto the event object - if (props) { - jQuery.extend(this, props); - } - - // Create a timestamp if incoming event doesn't have one - this.timeStamp = src && src.timeStamp || jQuery.now(); - - // Mark it as fixed - this[jQuery.expando] = true; - }; - jQuery.Tween = function Tween(elem, options, prop, end, easing) { - - return new Tween.prototype.init(elem, options, prop, end, easing); - }; - jQuery._data = function (elem, name, data) { - - return data_priv.access(elem, name, data); - }; - jQuery._evalUrl = function (url) { - - return jQuery.ajax({ - url: url, - type: "GET", - dataType: "text", - async: false, - global: false, - success: jQuery.globalEval - }); - }; - jQuery._queueHooks = function (elem, type) { - - var key = type + "queueHooks"; - return data_priv.get(elem, key) || data_priv.access(elem, key, { - empty: jQuery.Callbacks("once memory").add(function () { - data_priv.remove(elem, [type + "queue", key]); - }) - }); - }; - jQuery._removeData = function (elem, name) { - - data_priv.remove(elem, name); - }; - jQuery.acceptData = function (owner) { - - // Accepts only: - // - Node - // - Node.ELEMENT_NODE - // - Node.DOCUMENT_NODE - // - Object - // - Any - return owner.nodeType ? - owner.nodeType === 1 || owner.nodeType === 9 : true; - }; - jQuery.access = function (elems, fn, key, value, chainable, emptyGet, raw) { - - var i = 0, - length = elems.length, - bulk = key == null; - - // Sets many values - if (jQuery.type(key) === "object") { - chainable = true; - for (i in key) { - jQuery.access(elems, fn, i, key[i], true, emptyGet, raw); - } - - // Sets one value - } else if (value !== undefined) { - chainable = true; - - if (!jQuery.isFunction(value)) { - raw = true; - } - - if (bulk) { - // Bulk operations run against the entire set - if (raw) { - fn.call(elems, value); - fn = null; - - // ...except when executing function values - } else { - bulk = fn; - fn = function (elem, key, value) { - return bulk.call(jQuery(elem), value); - }; - } - } - - if (fn) { - for (; i < length; i++) { - fn(elems[i], key, raw ? value : value.call(elems[i], i, fn(elems[i], key))); - } - } - } - - return chainable ? - elems : - - // Gets - bulk ? - fn.call(elems) : - length ? fn(elems[0], key) : emptyGet; - }; - jQuery.active = 0; - jQuery.ajax = function (url, options) { - /// - /// Perform an asynchronous HTTP (Ajax) request. - /// 1 - jQuery.ajax(url, settings) - /// 2 - jQuery.ajax(settings) - /// - /// - /// A string containing the URL to which the request is sent. - /// - /// - /// A set of key/value pairs that configure the Ajax request. All settings are optional. A default can be set for any option with $.ajaxSetup(). See jQuery.ajax( settings ) below for a complete list of all settings. - /// - - - // If url is an object, simulate pre-1.5 signature - if (typeof url === "object") { - options = url; - url = undefined; - } - - // Force options to be an object - options = options || {}; - - var transport, - // URL without anti-cache param - cacheURL, - // Response headers - responseHeadersString, - responseHeaders, - // timeout handle - timeoutTimer, - // Cross-domain detection vars - parts, - // To know if global events are to be dispatched - fireGlobals, - // Loop variable - i, - // Create the final options object - s = jQuery.ajaxSetup({}, options), - // Callbacks context - callbackContext = s.context || s, - // Context for global events is callbackContext if it is a DOM node or jQuery collection - globalEventContext = s.context && (callbackContext.nodeType || callbackContext.jquery) ? - jQuery(callbackContext) : - jQuery.event, - // Deferreds - deferred = jQuery.Deferred(), - completeDeferred = jQuery.Callbacks("once memory"), - // Status-dependent callbacks - statusCode = s.statusCode || {}, - // Headers (they are sent all at once) - requestHeaders = {}, - requestHeadersNames = {}, - // The jqXHR state - state = 0, - // Default abort message - strAbort = "canceled", - // Fake xhr - jqXHR = { - readyState: 0, - - // Builds headers hashtable if needed - getResponseHeader: function (key) { - var match; - if (state === 2) { - if (!responseHeaders) { - responseHeaders = {}; - while ((match = rheaders.exec(responseHeadersString))) { - responseHeaders[match[1].toLowerCase()] = match[2]; - } - } - match = responseHeaders[key.toLowerCase()]; - } - return match == null ? null : match; - }, - - // Raw string - getAllResponseHeaders: function () { - return state === 2 ? responseHeadersString : null; - }, - - // Caches the header - setRequestHeader: function (name, value) { - var lname = name.toLowerCase(); - if (!state) { - name = requestHeadersNames[lname] = requestHeadersNames[lname] || name; - requestHeaders[name] = value; - } - return this; - }, - - // Overrides response content-type header - overrideMimeType: function (type) { - if (!state) { - s.mimeType = type; - } - return this; - }, - - // Status-dependent callbacks - statusCode: function (map) { - var code; - if (map) { - if (state < 2) { - for (code in map) { - // Lazy-add the new callback in a way that preserves old ones - statusCode[code] = [statusCode[code], map[code]]; - } - } else { - // Execute the appropriate callbacks - jqXHR.always(map[jqXHR.status]); - } - } - return this; - }, - - // Cancel the request - abort: function (statusText) { - var finalText = statusText || strAbort; - if (transport) { - transport.abort(finalText); - } - done(0, finalText); - return this; - } - }; - - // Attach deferreds - deferred.promise(jqXHR).complete = completeDeferred.add; - jqXHR.success = jqXHR.done; - jqXHR.error = jqXHR.fail; - - // Remove hash character (#7531: and string promotion) - // Add protocol if not provided (prefilters might expect it) - // Handle falsy url in the settings object (#10093: consistency with old signature) - // We also use the url parameter if available - s.url = ((url || s.url || ajaxLocation) + "").replace(rhash, "") - .replace(rprotocol, ajaxLocParts[1] + "//"); - - // Alias method option to type as per ticket #12004 - s.type = options.method || options.type || s.method || s.type; - - // Extract dataTypes list - s.dataTypes = jQuery.trim(s.dataType || "*").toLowerCase().match(core_rnotwhite) || [""]; - - // A cross-domain request is in order when we have a protocol:host:port mismatch - if (s.crossDomain == null) { - parts = rurl.exec(s.url.toLowerCase()); - s.crossDomain = !!(parts && - (parts[1] !== ajaxLocParts[1] || parts[2] !== ajaxLocParts[2] || - (parts[3] || (parts[1] === "http:" ? "80" : "443")) !== - (ajaxLocParts[3] || (ajaxLocParts[1] === "http:" ? "80" : "443"))) - ); - } - - // Convert data if not already a string - if (s.data && s.processData && typeof s.data !== "string") { - s.data = jQuery.param(s.data, s.traditional); - } - - // Apply prefilters - inspectPrefiltersOrTransports(prefilters, s, options, jqXHR); - - // If request was aborted inside a prefilter, stop there - if (state === 2) { - return jqXHR; - } - - // We can fire global events as of now if asked to - fireGlobals = s.global; - - // Watch for a new set of requests - if (fireGlobals && jQuery.active++ === 0) { - jQuery.event.trigger("ajaxStart"); - } - - // Uppercase the type - s.type = s.type.toUpperCase(); - - // Determine if request has content - s.hasContent = !rnoContent.test(s.type); - - // Save the URL in case we're toying with the If-Modified-Since - // and/or If-None-Match header later on - cacheURL = s.url; - - // More options handling for requests with no content - if (!s.hasContent) { - - // If data is available, append data to url - if (s.data) { - cacheURL = (s.url += (ajax_rquery.test(cacheURL) ? "&" : "?") + s.data); - // #9682: remove data so that it's not used in an eventual retry - delete s.data; - } - - // Add anti-cache in url if needed - if (s.cache === false) { - s.url = rts.test(cacheURL) ? - - // If there is already a '_' parameter, set its value - cacheURL.replace(rts, "$1_=" + ajax_nonce++) : - - // Otherwise add one to the end - cacheURL + (ajax_rquery.test(cacheURL) ? "&" : "?") + "_=" + ajax_nonce++; - } - } - - // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. - if (s.ifModified) { - if (jQuery.lastModified[cacheURL]) { - jqXHR.setRequestHeader("If-Modified-Since", jQuery.lastModified[cacheURL]); - } - if (jQuery.etag[cacheURL]) { - jqXHR.setRequestHeader("If-None-Match", jQuery.etag[cacheURL]); - } - } - - // Set the correct header, if data is being sent - if (s.data && s.hasContent && s.contentType !== false || options.contentType) { - jqXHR.setRequestHeader("Content-Type", s.contentType); - } - - // Set the Accepts header for the server, depending on the dataType - jqXHR.setRequestHeader( - "Accept", - s.dataTypes[0] && s.accepts[s.dataTypes[0]] ? - s.accepts[s.dataTypes[0]] + (s.dataTypes[0] !== "*" ? ", " + allTypes + "; q=0.01" : "") : - s.accepts["*"] - ); - - // Check for headers option - for (i in s.headers) { - jqXHR.setRequestHeader(i, s.headers[i]); - } - - // Allow custom headers/mimetypes and early abort - if (s.beforeSend && (s.beforeSend.call(callbackContext, jqXHR, s) === false || state === 2)) { - // Abort if not done already and return - return jqXHR.abort(); - } - - // aborting is no longer a cancellation - strAbort = "abort"; - - // Install callbacks on deferreds - for (i in { success: 1, error: 1, complete: 1 }) { - jqXHR[i](s[i]); - } - - // Get transport - transport = inspectPrefiltersOrTransports(transports, s, options, jqXHR); - - // If no transport, we auto-abort - if (!transport) { - done(-1, "No Transport"); - } else { - jqXHR.readyState = 1; - - // Send global event - if (fireGlobals) { - globalEventContext.trigger("ajaxSend", [jqXHR, s]); - } - // Timeout - if (s.async && s.timeout > 0) { - timeoutTimer = setTimeout(function () { - jqXHR.abort("timeout"); - }, s.timeout); - } - - try { - state = 1; - transport.send(requestHeaders, done); - } catch (e) { - // Propagate exception as error if not done - if (state < 2) { - done(-1, e); - // Simply rethrow otherwise - } else { - throw e; - } - } - } - - // Callback for when everything is done - function done(status, nativeStatusText, responses, headers) { - var isSuccess, success, error, response, modified, - statusText = nativeStatusText; - - // Called once - if (state === 2) { - return; - } - - // State is "done" now - state = 2; - - // Clear timeout if it exists - if (timeoutTimer) { - clearTimeout(timeoutTimer); - } - - // Dereference transport for early garbage collection - // (no matter how long the jqXHR object will be used) - transport = undefined; - - // Cache response headers - responseHeadersString = headers || ""; - - // Set readyState - jqXHR.readyState = status > 0 ? 4 : 0; - - // Determine if successful - isSuccess = status >= 200 && status < 300 || status === 304; - - // Get response data - if (responses) { - response = ajaxHandleResponses(s, jqXHR, responses); - } - - // Convert no matter what (that way responseXXX fields are always set) - response = ajaxConvert(s, response, jqXHR, isSuccess); - - // If successful, handle type chaining - if (isSuccess) { - - // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. - if (s.ifModified) { - modified = jqXHR.getResponseHeader("Last-Modified"); - if (modified) { - jQuery.lastModified[cacheURL] = modified; - } - modified = jqXHR.getResponseHeader("etag"); - if (modified) { - jQuery.etag[cacheURL] = modified; - } - } - - // if no content - if (status === 204) { - statusText = "nocontent"; - - // if not modified - } else if (status === 304) { - statusText = "notmodified"; - - // If we have data, let's convert it - } else { - statusText = response.state; - success = response.data; - error = response.error; - isSuccess = !error; - } - } else { - // We extract error from statusText - // then normalize statusText and status for non-aborts - error = statusText; - if (status || !statusText) { - statusText = "error"; - if (status < 0) { - status = 0; - } - } - } - - // Set data for the fake xhr object - jqXHR.status = status; - jqXHR.statusText = (nativeStatusText || statusText) + ""; - - // Success/Error - if (isSuccess) { - deferred.resolveWith(callbackContext, [success, statusText, jqXHR]); - } else { - deferred.rejectWith(callbackContext, [jqXHR, statusText, error]); - } - - // Status-dependent callbacks - jqXHR.statusCode(statusCode); - statusCode = undefined; - - if (fireGlobals) { - globalEventContext.trigger(isSuccess ? "ajaxSuccess" : "ajaxError", - [jqXHR, s, isSuccess ? success : error]); - } - - // Complete - completeDeferred.fireWith(callbackContext, [jqXHR, statusText]); - - if (fireGlobals) { - globalEventContext.trigger("ajaxComplete", [jqXHR, s]); - // Handle the global AJAX counter - if (!(--jQuery.active)) { - jQuery.event.trigger("ajaxStop"); - } - } - } - - return jqXHR; - }; - jQuery.ajaxPrefilter = function (dataTypeExpression, func) { - /// - /// Handle custom Ajax options or modify existing options before each request is sent and before they are processed by $.ajax(). - /// - /// - /// An optional string containing one or more space-separated dataTypes - /// - /// - /// A handler to set default values for future Ajax requests. - /// - /// - - - if (typeof dataTypeExpression !== "string") { - func = dataTypeExpression; - dataTypeExpression = "*"; - } - - var dataType, - i = 0, - dataTypes = dataTypeExpression.toLowerCase().match(core_rnotwhite) || []; - - if (jQuery.isFunction(func)) { - // For each dataType in the dataTypeExpression - while ((dataType = dataTypes[i++])) { - // Prepend if requested - if (dataType[0] === "+") { - dataType = dataType.slice(1) || "*"; - (structure[dataType] = structure[dataType] || []).unshift(func); - - // Otherwise append - } else { - (structure[dataType] = structure[dataType] || []).push(func); - } - } - } - }; - jQuery.ajaxSettings = { - "url": 'http://localhost:25812/?ver=3.1.0&newLineMethod=xml', - "type": 'GET', - "isLocal": false, - "global": true, - "processData": true, - "async": true, - "contentType": 'application/x-www-form-urlencoded; charset=UTF-8', - "accepts": {}, - "contents": {}, - "responseFields": {}, - "converters": {}, - "flatOptions": {}, - "jsonp": 'callback' - }; - jQuery.ajaxSetup = function (target, settings) { - /// - /// Set default values for future Ajax requests. Its use is not recommended. - /// - /// - /// A set of key/value pairs that configure the default Ajax request. All options are optional. - /// - - return settings ? - - // Building a settings object - ajaxExtend(ajaxExtend(target, jQuery.ajaxSettings), settings) : - - // Extending ajaxSettings - ajaxExtend(jQuery.ajaxSettings, target); - }; - jQuery.ajaxTransport = function (dataTypeExpression, func) { - /// - /// Creates an object that handles the actual transmission of Ajax data. - /// - /// - /// A string identifying the data type to use - /// - /// - /// A handler to return the new transport object to use with the data type provided in the first argument. - /// - /// - - - if (typeof dataTypeExpression !== "string") { - func = dataTypeExpression; - dataTypeExpression = "*"; - } - - var dataType, - i = 0, - dataTypes = dataTypeExpression.toLowerCase().match(core_rnotwhite) || []; - - if (jQuery.isFunction(func)) { - // For each dataType in the dataTypeExpression - while ((dataType = dataTypes[i++])) { - // Prepend if requested - if (dataType[0] === "+") { - dataType = dataType.slice(1) || "*"; - (structure[dataType] = structure[dataType] || []).unshift(func); - - // Otherwise append - } else { - (structure[dataType] = structure[dataType] || []).push(func); - } - } - } - }; - jQuery.attr = function (elem, name, value) { - - var hooks, ret, - nType = elem.nodeType; - - // don't get/set attributes on text, comment and attribute nodes - if (!elem || nType === 3 || nType === 8 || nType === 2) { - return; - } - - // Fallback to prop when attributes are not supported - if (typeof elem.getAttribute === core_strundefined) { - return jQuery.prop(elem, name, value); - } - - // All attributes are lowercase - // Grab necessary hook if one is defined - if (nType !== 1 || !jQuery.isXMLDoc(elem)) { - name = name.toLowerCase(); - hooks = jQuery.attrHooks[name] || - (jQuery.expr.match.boolean.test(name) ? boolHook : nodeHook); - } - - if (value !== undefined) { - - if (value === null) { - jQuery.removeAttr(elem, name); - - } else if (hooks && "set" in hooks && (ret = hooks.set(elem, value, name)) !== undefined) { - return ret; - - } else { - elem.setAttribute(name, value + ""); - return value; - } - - } else if (hooks && "get" in hooks && (ret = hooks.get(elem, name)) !== null) { - return ret; - - } else { - ret = jQuery.find.attr(elem, name); - - // Non-existent attributes return null, we normalize to undefined - return ret == null ? - undefined : - ret; - } - }; - jQuery.attrHooks = { "type": {} }; - jQuery.buildFragment = function (elems, context, scripts, selection) { - - var elem, tmp, tag, wrap, contains, j, - i = 0, - l = elems.length, - fragment = context.createDocumentFragment(), - nodes = []; - - for (; i < l; i++) { - elem = elems[i]; - - if (elem || elem === 0) { - - // Add nodes directly - if (jQuery.type(elem) === "object") { - // Support: QtWebKit - // jQuery.merge because core_push.apply(_, arraylike) throws - jQuery.merge(nodes, elem.nodeType ? [elem] : elem); - - // Convert non-html into a text node - } else if (!rhtml.test(elem)) { - nodes.push(context.createTextNode(elem)); - - // Convert html into DOM nodes - } else { - tmp = tmp || fragment.appendChild(context.createElement("div")); - - // Deserialize a standard representation - tag = (rtagName.exec(elem) || ["", ""])[1].toLowerCase(); - wrap = wrapMap[tag] || wrapMap._default; - tmp.innerHTML = wrap[1] + elem.replace(rxhtmlTag, "<$1>") + wrap[2]; - - // Descend through wrappers to the right content - j = wrap[0]; - while (j--) { - tmp = tmp.firstChild; - } - - // Support: QtWebKit - // jQuery.merge because core_push.apply(_, arraylike) throws - jQuery.merge(nodes, tmp.childNodes); - - // Remember the top-level container - tmp = fragment.firstChild; - - // Fixes #12346 - // Support: Webkit, IE - tmp.textContent = ""; - } - } - } - - // Remove wrapper from fragment - fragment.textContent = ""; - - i = 0; - while ((elem = nodes[i++])) { - - // #4087 - If origin and destination elements are the same, and this is - // that element, do not do anything - if (selection && jQuery.inArray(elem, selection) !== -1) { - continue; - } - - contains = jQuery.contains(elem.ownerDocument, elem); - - // Append to fragment - tmp = getAll(fragment.appendChild(elem), "script"); - - // Preserve script evaluation history - if (contains) { - setGlobalEval(tmp); - } - - // Capture executables - if (scripts) { - j = 0; - while ((elem = tmp[j++])) { - if (rscriptType.test(elem.type || "")) { - scripts.push(elem); - } - } - } - } - - return fragment; - }; - jQuery.camelCase = function (string) { - - return string.replace(rmsPrefix, "ms-").replace(rdashAlpha, fcamelCase); - }; - jQuery.cleanData = function (elems) { - - var data, elem, type, - l = elems.length, - i = 0, - special = jQuery.event.special; - - for (; i < l; i++) { - elem = elems[i]; - - if (jQuery.acceptData(elem)) { - - data = data_priv.access(elem); - - if (data) { - for (type in data.events) { - if (special[type]) { - jQuery.event.remove(elem, type); - - // This is a shortcut to avoid jQuery.event.remove's overhead - } else { - jQuery.removeEvent(elem, type, data.handle); - } - } - } - } - // Discard any remaining `private` and `user` data - // One day we'll replace the dual arrays with a WeakMap and this won't be an issue. - // (Splices the data objects out of the internal cache arrays) - data_user.discard(elem); - data_priv.discard(elem); - } - }; - jQuery.clone = function (elem, dataAndEvents, deepDataAndEvents) { - - var i, l, srcElements, destElements, - clone = elem.cloneNode(true), - inPage = jQuery.contains(elem.ownerDocument, elem); - - // Support: IE >= 9 - // Fix Cloning issues - if (!jQuery.support.noCloneChecked && (elem.nodeType === 1 || elem.nodeType === 11) && !jQuery.isXMLDoc(elem)) { - - // We eschew Sizzle here for performance reasons: http://jsperf.com/getall-vs-sizzle/2 - destElements = getAll(clone); - srcElements = getAll(elem); - - for (i = 0, l = srcElements.length; i < l; i++) { - fixInput(srcElements[i], destElements[i]); - } - } - - // Copy the events from the original to the clone - if (dataAndEvents) { - if (deepDataAndEvents) { - srcElements = srcElements || getAll(elem); - destElements = destElements || getAll(clone); - - for (i = 0, l = srcElements.length; i < l; i++) { - cloneCopyEvent(srcElements[i], destElements[i]); - } - } else { - cloneCopyEvent(elem, clone); - } - } - - // Preserve script evaluation history - destElements = getAll(clone, "script"); - if (destElements.length > 0) { - setGlobalEval(destElements, !inPage && getAll(elem, "script")); - } - - // Return the cloned set - return clone; - }; - jQuery.contains = function (context, elem) { - /// - /// Check to see if a DOM element is a descendant of another DOM element. - /// - /// - /// The DOM element that may contain the other element. - /// - /// - /// The DOM element that may be contained by (a descendant of) the other element. - /// - /// - - // Set document vars if needed - if ((context.ownerDocument || context) !== document) { - setDocument(context); - } - return contains(context, elem); - }; - jQuery.css = function (elem, name, extra, styles) { - - var val, num, hooks, - origName = jQuery.camelCase(name); - - // Make sure that we're working with the right name - name = jQuery.cssProps[origName] || (jQuery.cssProps[origName] = vendorPropName(elem.style, origName)); - - // gets hook for the prefixed version - // followed by the unprefixed version - hooks = jQuery.cssHooks[name] || jQuery.cssHooks[origName]; - - // If a hook was provided get the computed value from there - if (hooks && "get" in hooks) { - val = hooks.get(elem, true, extra); - } - - // Otherwise, if a way to get the computed value exists, use that - if (val === undefined) { - val = curCSS(elem, name, styles); - } - - //convert "normal" to computed value - if (val === "normal" && name in cssNormalTransform) { - val = cssNormalTransform[name]; - } - - // Return, converting to number if forced or a qualifier was provided and val looks numeric - if (extra === "" || extra) { - num = parseFloat(val); - return extra === true || jQuery.isNumeric(num) ? num || 0 : val; - } - return val; - }; - jQuery.cssHooks = { - "opacity": {}, - "height": {}, - "width": {}, - "margin": {}, - "padding": {}, - "borderWidth": {}, - "top": {}, - "left": {} - }; - jQuery.cssNumber = { - "columnCount": true, - "fillOpacity": true, - "fontWeight": true, - "lineHeight": true, - "opacity": true, - "orphans": true, - "widows": true, - "zIndex": true, - "zoom": true - }; - jQuery.cssProps = { - "float": 'cssFloat', - "display": 'display', - "visibility": 'visibility' - }; - jQuery.data = function (elem, name, data) { - /// - /// 1: Store arbitrary data associated with the specified element. Returns the value that was set. - /// 1.1 - jQuery.data(element, key, value) - /// 2: Returns value at named data store for the element, as set by jQuery.data(element, name, value), or the full data store for the element. - /// 2.1 - jQuery.data(element, key) - /// 2.2 - jQuery.data(element) - /// - /// - /// The DOM element to associate with the data. - /// - /// - /// A string naming the piece of data to set. - /// - /// - /// The new data value. - /// - /// - - return data_user.access(elem, name, data); - }; - jQuery.dequeue = function (elem, type) { - /// - /// Execute the next function on the queue for the matched element. - /// - /// - /// A DOM element from which to remove and execute a queued function. - /// - /// - /// A string containing the name of the queue. Defaults to fx, the standard effects queue. - /// - /// - - type = type || "fx"; - - var queue = jQuery.queue(elem, type), - startLength = queue.length, - fn = queue.shift(), - hooks = jQuery._queueHooks(elem, type), - next = function () { - jQuery.dequeue(elem, type); - }; - - // If the fx queue is dequeued, always remove the progress sentinel - if (fn === "inprogress") { - fn = queue.shift(); - startLength--; - } - - hooks.cur = fn; - if (fn) { - - // Add a progress sentinel to prevent the fx queue from being - // automatically dequeued - if (type === "fx") { - queue.unshift("inprogress"); - } - - // clear up the last queue stop function - delete hooks.stop; - fn.call(elem, next, hooks); - } - - if (!startLength && hooks) { - hooks.empty.fire(); - } - }; - jQuery.dir = function (elem, dir, until) { - - var matched = [], - truncate = until !== undefined; - - while ((elem = elem[dir]) && elem.nodeType !== 9) { - if (elem.nodeType === 1) { - if (truncate && jQuery(elem).is(until)) { - break; - } - matched.push(elem); - } - } - return matched; - }; - jQuery.each = function (obj, callback, args) { - /// - /// A generic iterator function, which can be used to seamlessly iterate over both objects and arrays. Arrays and array-like objects with a length property (such as a function's arguments object) are iterated by numeric index, from 0 to length-1. Other objects are iterated via their named properties. - /// - /// - /// The object or array to iterate over. - /// - /// - /// The function that will be executed on every object. - /// - /// - - var value, - i = 0, - length = obj.length, - isArray = isArraylike(obj); - - if (args) { - if (isArray) { - for (; i < length; i++) { - value = callback.apply(obj[i], args); - - if (value === false) { - break; - } - } - } else { - for (i in obj) { - value = callback.apply(obj[i], args); - - if (value === false) { - break; - } - } - } - - // A special, fast, case for the most common use of each - } else { - if (isArray) { - for (; i < length; i++) { - value = callback.call(obj[i], i, obj[i]); - - if (value === false) { - break; - } - } - } else { - for (i in obj) { - value = callback.call(obj[i], i, obj[i]); - - if (value === false) { - break; - } - } - } - } - - return obj; - }; - jQuery.easing = {}; - jQuery.error = function (msg) { - /// - /// Takes a string and throws an exception containing it. - /// - /// - /// The message to send out. - /// - - throw new Error(msg); - }; - jQuery.etag = {}; - jQuery.event = { - "global": {}, - "props": ['altKey', 'bubbles', 'cancelable', 'ctrlKey', 'currentTarget', 'eventPhase', 'metaKey', 'relatedTarget', 'shiftKey', 'target', 'timeStamp', 'view', 'which'], - "fixHooks": {}, - "keyHooks": {}, - "mouseHooks": {}, - "special": {}, - "triggered": {} - }; - jQuery.expr = { - "cacheLength": 50, - "match": {}, - "attrHandle": {}, - "find": {}, - "relative": {}, - "preFilter": {}, - "filter": {}, - "pseudos": {}, - "filters": {}, - "setFilters": {}, - ":": {} - }; - jQuery.extend = function () { - /// - /// Merge the contents of two or more objects together into the first object. - /// 1 - jQuery.extend(target, object1, objectN) - /// 2 - jQuery.extend(deep, target, object1, objectN) - /// - /// - /// If true, the merge becomes recursive (aka. deep copy). - /// - /// - /// The object to extend. It will receive the new properties. - /// - /// - /// An object containing additional properties to merge in. - /// - /// - /// Additional objects containing properties to merge in. - /// - /// - - var options, name, src, copy, copyIsArray, clone, - target = arguments[0] || {}, - i = 1, - length = arguments.length, - deep = false; - - // Handle a deep copy situation - if (typeof target === "boolean") { - deep = target; - target = arguments[1] || {}; - // skip the boolean and the target - i = 2; - } - - // Handle case when target is a string or something (possible in deep copy) - if (typeof target !== "object" && !jQuery.isFunction(target)) { - target = {}; - } - - // extend jQuery itself if only one argument is passed - if (length === i) { - target = this; - --i; - } - - for (; i < length; i++) { - // Only deal with non-null/undefined values - if ((options = arguments[i]) != null) { - // Extend the base object - for (name in options) { - src = target[name]; - copy = options[name]; - - // Prevent never-ending loop - if (target === copy) { - continue; - } - - // Recurse if we're merging plain objects or arrays - if (deep && copy && (jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)))) { - if (copyIsArray) { - copyIsArray = false; - clone = src && jQuery.isArray(src) ? src : []; - - } else { - clone = src && jQuery.isPlainObject(src) ? src : {}; - } - - // Never move original objects, clone them - target[name] = jQuery.extend(deep, clone, copy); - - // Don't bring in undefined values - } else if (copy !== undefined) { - target[name] = copy; - } - } - } - } - - // Return the modified object - return target; - }; - jQuery.filter = function (expr, elems, not) { - - var elem = elems[0]; - - if (not) { - expr = ":not(" + expr + ")"; - } - - return elems.length === 1 && elem.nodeType === 1 ? - jQuery.find.matchesSelector(elem, expr) ? [elem] : [] : - jQuery.find.matches(expr, jQuery.grep(elems, function (elem) { - return elem.nodeType === 1; - })); - }; - jQuery.find = function Sizzle(selector, context, results, seed) { - - var match, elem, m, nodeType, - // QSA vars - i, groups, old, nid, newContext, newSelector; - - if ((context ? context.ownerDocument || context : preferredDoc) !== document) { - setDocument(context); - } - - context = context || document; - results = results || []; - - if (!selector || typeof selector !== "string") { - return results; - } - - if ((nodeType = context.nodeType) !== 1 && nodeType !== 9) { - return []; - } - - if (documentIsHTML && !seed) { - - // Shortcuts - if ((match = rquickExpr.exec(selector))) { - // Speed-up: Sizzle("#ID") - if ((m = match[1])) { - if (nodeType === 9) { - elem = context.getElementById(m); - // Check parentNode to catch when Blackberry 4.6 returns - // nodes that are no longer in the document #6963 - if (elem && elem.parentNode) { - // Handle the case where IE, Opera, and Webkit return items - // by name instead of ID - if (elem.id === m) { - results.push(elem); - return results; - } - } else { - return results; - } - } else { - // Context is not a document - if (context.ownerDocument && (elem = context.ownerDocument.getElementById(m)) && - contains(context, elem) && elem.id === m) { - results.push(elem); - return results; - } - } - - // Speed-up: Sizzle("TAG") - } else if (match[2]) { - push.apply(results, context.getElementsByTagName(selector)); - return results; - - // Speed-up: Sizzle(".CLASS") - } else if ((m = match[3]) && support.getElementsByClassName && context.getElementsByClassName) { - push.apply(results, context.getElementsByClassName(m)); - return results; - } - } - - // QSA path - if (support.qsa && (!rbuggyQSA || !rbuggyQSA.test(selector))) { - nid = old = expando; - newContext = context; - newSelector = nodeType === 9 && selector; - - // qSA works strangely on Element-rooted queries - // We can work around this by specifying an extra ID on the root - // and working up from there (Thanks to Andrew Dupont for the technique) - // IE 8 doesn't work on object elements - if (nodeType === 1 && context.nodeName.toLowerCase() !== "object") { - groups = tokenize(selector); - - if ((old = context.getAttribute("id"))) { - nid = old.replace(rescape, "\\$&"); - } else { - context.setAttribute("id", nid); - } - nid = "[id='" + nid + "'] "; - - i = groups.length; - while (i--) { - groups[i] = nid + toSelector(groups[i]); - } - newContext = rsibling.test(selector) && context.parentNode || context; - newSelector = groups.join(","); - } - - if (newSelector) { - try { - push.apply(results, - newContext.querySelectorAll(newSelector) - ); - return results; - } catch (qsaError) { - } finally { - if (!old) { - context.removeAttribute("id"); - } - } - } - } - } - - // All others - return select(selector.replace(rtrim, "$1"), context, results, seed); - }; - jQuery.fn = { - "jquery": '3.4.1', - "selector": '', - "length": 0 - }; - jQuery.fx = function (elem, options, prop, end, easing, unit) { - - this.elem = elem; - this.prop = prop; - this.easing = easing || "swing"; - this.options = options; - this.start = this.now = this.cur(); - this.end = end; - this.unit = unit || (jQuery.cssNumber[prop] ? "" : "px"); - }; - jQuery.get = function (url, data, callback, type) { - /// - /// Load data from the server using a HTTP GET request. - /// - /// - /// A string containing the URL to which the request is sent. - /// - /// - /// A plain object or string that is sent to the server with the request. - /// - /// - /// A callback function that is executed if the request succeeds. - /// - /// - /// The type of data expected from the server. Default: Intelligent Guess (xml, json, script, or html). - /// - - // shift arguments if data argument was omitted - if (jQuery.isFunction(data)) { - type = type || callback; - callback = data; - data = undefined; - } - - return jQuery.ajax({ - url: url, - type: method, - dataType: type, - data: data, - success: callback - }); - }; - jQuery.getJSON = function (url, data, callback) { - /// - /// Load JSON-encoded data from the server using a GET HTTP request. - /// - /// - /// A string containing the URL to which the request is sent. - /// - /// - /// A plain object or string that is sent to the server with the request. - /// - /// - /// A callback function that is executed if the request succeeds. - /// - - return jQuery.get(url, data, callback, "json"); - }; - jQuery.getScript = function (url, callback) { - /// - /// Load a JavaScript file from the server using a GET HTTP request, then execute it. - /// - /// - /// A string containing the URL to which the request is sent. - /// - /// - /// A callback function that is executed if the request succeeds. - /// - - return jQuery.get(url, undefined, callback, "script"); - }; - jQuery.globalEval = function (code) { - /// - /// Execute some JavaScript code globally. - /// - /// - /// The JavaScript code to execute. - /// - - var script, - indirect = eval; - - code = jQuery.trim(code); - - if (code) { - // If the code includes a valid, prologue position - // strict mode pragma, execute code by injecting a - // script tag into the document. - if (code.indexOf("use strict") === 1) { - script = document.createElement("script"); - script.text = code; - document.head.appendChild(script).parentNode.removeChild(script); - } else { - // Otherwise, avoid the DOM node creation, insertion - // and removal by using an indirect global eval - indirect(code); - } - } - }; - jQuery.grep = function (elems, callback, inv) { - /// - /// Finds the elements of an array which satisfy a filter function. The original array is not affected. - /// - /// - /// The array to search through. - /// - /// - /// The function to process each item against. The first argument to the function is the item, and the second argument is the index. The function should return a Boolean value. this will be the global window object. - /// - /// - /// If "invert" is false, or not provided, then the function returns an array consisting of all elements for which "callback" returns true. If "invert" is true, then the function returns an array consisting of all elements for which "callback" returns false. - /// - /// - - var retVal, - ret = [], - i = 0, - length = elems.length; - inv = !!inv; - - // Go through the array, only saving the items - // that pass the validator function - for (; i < length; i++) { - retVal = !!callback(elems[i], i); - if (inv !== retVal) { - ret.push(elems[i]); - } - } - - return ret; - }; - jQuery.guid = 1; - jQuery.hasData = function (elem) { - /// - /// Determine whether an element has any jQuery data associated with it. - /// - /// - /// A DOM element to be checked for data. - /// - /// - - return data_user.hasData(elem) || data_priv.hasData(elem); - }; - jQuery.holdReady = function (hold) { - /// - /// Holds or releases the execution of jQuery's ready event. - /// - /// - /// Indicates whether the ready hold is being requested or released - /// - /// - - if (hold) { - jQuery.readyWait++; - } else { - jQuery.ready(true); - } - }; - jQuery.inArray = function (elem, arr, i) { - /// - /// Search for a specified value within an array and return its index (or -1 if not found). - /// - /// - /// The value to search for. - /// - /// - /// An array through which to search. - /// - /// - /// The index of the array at which to begin the search. The default is 0, which will search the whole array. - /// - /// - - return arr == null ? -1 : core_indexOf.call(arr, elem, i); - }; - jQuery.isEmptyObject = function (obj) { - /// - /// Check to see if an object is empty (contains no enumerable properties). - /// - /// - /// The object that will be checked to see if it's empty. - /// - /// - - var name; - for (name in obj) { - return false; - } - return true; - }; - jQuery.isFunction = function (obj) { - /// - /// Determine if the argument passed is a Javascript function object. - /// - /// - /// Object to test whether or not it is a function. - /// - /// - - return jQuery.type(obj) === "function"; - }; - jQuery.isNumeric = function (obj) { - /// - /// Determines whether its argument is a number. - /// - /// - /// The value to be tested. - /// - /// - - return !isNaN(parseFloat(obj)) && isFinite(obj); - }; - jQuery.isPlainObject = function (obj) { - /// - /// Check to see if an object is a plain object (created using "{}" or "new Object"). - /// - /// - /// The object that will be checked to see if it's a plain object. - /// - /// - - // Not plain objects: - // - Any object or value whose internal [[Class]] property is not "[object Object]" - // - DOM nodes - // - window - if (jQuery.type(obj) !== "object" || obj.nodeType || jQuery.isWindow(obj)) { - return false; - } - - // Support: Firefox <20 - // The try/catch suppresses exceptions thrown when attempting to access - // the "constructor" property of certain host objects, ie. |window.location| - // https://bugzilla.mozilla.org/show_bug.cgi?id=814622 - try { - if (obj.constructor && - !core_hasOwn.call(obj.constructor.prototype, "isPrototypeOf")) { - return false; - } - } catch (e) { - return false; - } - - // If the function hasn't returned already, we're confident that - // |obj| is a plain object, created by {} or constructed with new Object - return true; - }; - jQuery.isReady = true; - jQuery.isWindow = function (obj) { - /// - /// Determine whether the argument is a window. - /// - /// - /// Object to test whether or not it is a window. - /// - /// - - return obj != null && obj === obj.window; - }; - jQuery.isXMLDoc = function (elem) { - /// - /// Check to see if a DOM node is within an XML document (or is an XML document). - /// - /// - /// The DOM node that will be checked to see if it's in an XML document. - /// - /// - - // documentElement is verified for cases where it doesn't yet exist - // (such as loading iframes in IE - #4833) - var documentElement = elem && (elem.ownerDocument || elem).documentElement; - return documentElement ? documentElement.nodeName !== "HTML" : false; - }; - jQuery.lastModified = {}; - jQuery.makeArray = function (arr, results) { - /// - /// Convert an array-like object into a true JavaScript array. - /// - /// - /// Any object to turn into a native Array. - /// - /// - - var ret = results || []; - - if (arr != null) { - if (isArraylike(Object(arr))) { - jQuery.merge(ret, - typeof arr === "string" ? - [arr] : arr - ); - } else { - core_push.call(ret, arr); - } - } - - return ret; - }; - jQuery.map = function (elems, callback, arg) { - /// - /// Translate all items in an array or object to new array of items. - /// 1 - jQuery.map(array, callback(elementOfArray, indexInArray)) - /// 2 - jQuery.map(arrayOrObject, callback( value, indexOrKey )) - /// - /// - /// The Array to translate. - /// - /// - /// The function to process each item against. The first argument to the function is the array item, the second argument is the index in array The function can return any value. Within the function, this refers to the global (window) object. - /// - /// - - var value, - i = 0, - length = elems.length, - isArray = isArraylike(elems), - ret = []; - - // Go through the array, translating each of the items to their - if (isArray) { - for (; i < length; i++) { - value = callback(elems[i], i, arg); - - if (value != null) { - ret[ret.length] = value; - } - } - - // Go through every key on the object, - } else { - for (i in elems) { - value = callback(elems[i], i, arg); - - if (value != null) { - ret[ret.length] = value; - } - } - } - - // Flatten any nested arrays - return core_concat.apply([], ret); - }; - jQuery.merge = function (first, second) { - /// - /// Merge the contents of two arrays together into the first array. - /// - /// - /// The first array to merge, the elements of second added. - /// - /// - /// The second array to merge into the first, unaltered. - /// - /// - - var l = second.length, - i = first.length, - j = 0; - - if (typeof l === "number") { - for (; j < l; j++) { - first[i++] = second[j]; - } - } else { - while (second[j] !== undefined) { - first[i++] = second[j++]; - } - } - - first.length = i; - - return first; - }; - jQuery.noConflict = function (deep) { - /// - /// Relinquish jQuery's control of the $ variable. - /// - /// - /// A Boolean indicating whether to remove all jQuery variables from the global scope (including jQuery itself). - /// - /// - - if (window.$ === jQuery) { - window.$ = _$; - } - - if (deep && window.jQuery === jQuery) { - window.jQuery = _jQuery; - } - - return jQuery; - }; - jQuery.nodeName = function (elem, name) { - - return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase(); - }; - jQuery.noop = function () { - /// - /// An empty function. - /// - /// - }; - jQuery.offset = {}; - jQuery.param = function (a, traditional) { - /// - /// Create a serialized representation of an array or object, suitable for use in a URL query string or Ajax request. - /// 1 - jQuery.param(obj) - /// 2 - jQuery.param(obj, traditional) - /// - /// - /// An array or object to serialize. - /// - /// - /// A Boolean indicating whether to perform a traditional "shallow" serialization. - /// - /// - - var prefix, - s = [], - add = function (key, value) { - // If value is a function, invoke it and return its value - value = jQuery.isFunction(value) ? value() : (value == null ? "" : value); - s[s.length] = encodeURIComponent(key) + "=" + encodeURIComponent(value); - }; - - // Set traditional to true for jQuery <= 1.3.2 behavior. - if (traditional === undefined) { - traditional = jQuery.ajaxSettings && jQuery.ajaxSettings.traditional; - } - - // If an array was passed in, assume that it is an array of form elements. - if (jQuery.isArray(a) || (a.jquery && !jQuery.isPlainObject(a))) { - // Serialize the form elements - jQuery.each(a, function () { - add(this.name, this.value); - }); - - } else { - // If traditional, encode the "old" way (the way 1.3.2 or older - // did it), otherwise encode params recursively. - for (prefix in a) { - buildParams(prefix, a[prefix], traditional, add); - } - } - - // Return the resulting serialization - return s.join("&").replace(r20, "+"); - }; - jQuery.parseHTML = function (data, context, keepScripts) { - /// - /// Parses a string into an array of DOM nodes. - /// - /// - /// HTML string to be parsed - /// - /// - /// DOM element to serve as the context in which the HTML fragment will be created - /// - /// - /// A Boolean indicating whether to include scripts passed in the HTML string - /// - /// - - if (!data || typeof data !== "string") { - return null; - } - if (typeof context === "boolean") { - keepScripts = context; - context = false; - } - context = context || document; - - var parsed = rsingleTag.exec(data), - scripts = !keepScripts && []; - - // Single tag - if (parsed) { - return [context.createElement(parsed[1])]; - } - - parsed = jQuery.buildFragment([data], context, scripts); - - if (scripts) { - jQuery(scripts).remove(); - } - - return jQuery.merge([], parsed.childNodes); - }; - jQuery.parseXML = function (data) { - /// - /// Parses a string into an XML document. - /// - /// - /// a well-formed XML string to be parsed - /// - /// - - var xml, tmp; - if (!data || typeof data !== "string") { - return null; - } - - // Support: IE9 - try { - tmp = new DOMParser(); - xml = tmp.parseFromString(data, "text/xml"); - } catch (e) { - xml = undefined; - } - - if (!xml || xml.getElementsByTagName("parsererror").length) { - jQuery.error("Invalid XML: " + data); - } - return xml; - }; - jQuery.post = function (url, data, callback, type) { - /// - /// Load data from the server using a HTTP POST request. - /// - /// - /// A string containing the URL to which the request is sent. - /// - /// - /// A plain object or string that is sent to the server with the request. - /// - /// - /// A callback function that is executed if the request succeeds. - /// - /// - /// The type of data expected from the server. Default: Intelligent Guess (xml, json, script, text, html). - /// - - // shift arguments if data argument was omitted - if (jQuery.isFunction(data)) { - type = type || callback; - callback = data; - data = undefined; - } - - return jQuery.ajax({ - url: url, - type: method, - dataType: type, - data: data, - success: callback - }); - }; - jQuery.prop = function (elem, name, value) { - - var ret, hooks, notxml, - nType = elem.nodeType; - - // don't get/set properties on text, comment and attribute nodes - if (!elem || nType === 3 || nType === 8 || nType === 2) { - return; - } - - notxml = nType !== 1 || !jQuery.isXMLDoc(elem); - - if (notxml) { - // Fix name and attach hooks - name = jQuery.propFix[name] || name; - hooks = jQuery.propHooks[name]; - } - - if (value !== undefined) { - return hooks && "set" in hooks && (ret = hooks.set(elem, value, name)) !== undefined ? - ret : - (elem[name] = value); - - } else { - return hooks && "get" in hooks && (ret = hooks.get(elem, name)) !== null ? - ret : - elem[name]; - } - }; - jQuery.propFix = { - "for": 'htmlFor', - "class": 'className', - "tabindex": {}, - "readonly": {}, - "maxlength": {}, - "cellspacing": {}, - "cellpadding": {}, - "rowspan": {}, - "colspan": {}, - "usemap": {}, - "frameborder": {}, - "contenteditable": {} - }; - jQuery.propHooks = { "tabIndex": {} }; - jQuery.proxy = function (fn, context) { - /// - /// Takes a function and returns a new one that will always have a particular context. - /// 1 - jQuery.proxy(function, context) - /// 2 - jQuery.proxy(context, name) - /// 3 - jQuery.proxy(function, context, additionalArguments) - /// 4 - jQuery.proxy(context, name, additionalArguments) - /// - /// - /// The function whose context will be changed. - /// - /// - /// The object to which the context (this) of the function should be set. - /// - /// - /// Any number of arguments to be passed to the function referenced in the function argument. - /// - /// - - var tmp, args, proxy; - - if (typeof context === "string") { - tmp = fn[context]; - context = fn; - fn = tmp; - } - - // Quick check to determine if target is callable, in the spec - // this throws a TypeError, but we will just return undefined. - if (!jQuery.isFunction(fn)) { - return undefined; - } - - // Simulated bind - args = core_slice.call(arguments, 2); - proxy = function () { - return fn.apply(context || this, args.concat(core_slice.call(arguments))); - }; - - // Set the guid of unique handler to the same of original handler, so it can be removed - proxy.guid = fn.guid = fn.guid || jQuery.guid++; - - return proxy; - }; - jQuery.queue = function (elem, type, data) { - /// - /// 1: Show the queue of functions to be executed on the matched element. - /// 1.1 - jQuery.queue(element, queueName) - /// 2: Manipulate the queue of functions to be executed on the matched element. - /// 2.1 - jQuery.queue(element, queueName, newQueue) - /// 2.2 - jQuery.queue(element, queueName, callback()) - /// - /// - /// A DOM element where the array of queued functions is attached. - /// - /// - /// A string containing the name of the queue. Defaults to fx, the standard effects queue. - /// - /// - /// An array of functions to replace the current queue contents. - /// - /// - - var queue; - - if (elem) { - type = (type || "fx") + "queue"; - queue = data_priv.get(elem, type); - - // Speed up dequeue by getting out quickly if this is just a lookup - if (data) { - if (!queue || jQuery.isArray(data)) { - queue = data_priv.access(elem, type, jQuery.makeArray(data)); - } else { - queue.push(data); - } - } - return queue || []; - } - }; - jQuery.ready = function (wait) { - - - // Abort if there are pending holds or we're already ready - if (wait === true ? --jQuery.readyWait : jQuery.isReady) { - return; - } - - // Remember that the DOM is ready - jQuery.isReady = true; - - // If a normal DOM Ready event fired, decrement, and wait if need be - if (wait !== true && --jQuery.readyWait > 0) { - return; - } - - // If there are functions bound, to execute - readyList.resolveWith(document, [jQuery]); - - // Trigger any bound ready events - if (jQuery.fn.trigger) { - jQuery(document).trigger("ready").off("ready"); - } - }; - jQuery.readyWait = 0; - jQuery.removeAttr = function (elem, value) { - - var name, propName, - i = 0, - attrNames = value && value.match(core_rnotwhite); - - if (attrNames && elem.nodeType === 1) { - while ((name = attrNames[i++])) { - propName = jQuery.propFix[name] || name; - - // Boolean attributes get special treatment (#10870) - if (jQuery.expr.match.boolean.test(name)) { - // Set corresponding property to false - elem[propName] = false; - } - - elem.removeAttribute(name); - } - } - }; - jQuery.removeData = function (elem, name) { - /// - /// Remove a previously-stored piece of data. - /// - /// - /// A DOM element from which to remove data. - /// - /// - /// A string naming the piece of data to remove. - /// - /// - - data_user.remove(elem, name); - }; - jQuery.removeEvent = function (elem, type, handle) { - - if (elem.removeEventListener) { - elem.removeEventListener(type, handle, false); - } - }; - jQuery.sibling = function (n, elem) { - - var matched = []; - - for (; n; n = n.nextSibling) { - if (n.nodeType === 1 && n !== elem) { - matched.push(n); - } - } - - return matched; - }; - jQuery.speed = function (speed, easing, fn) { - - var opt = speed && typeof speed === "object" ? jQuery.extend({}, speed) : { - complete: fn || !fn && easing || - jQuery.isFunction(speed) && speed, - duration: speed, - easing: fn && easing || easing && !jQuery.isFunction(easing) && easing - }; - - opt.duration = jQuery.fx.off ? 0 : typeof opt.duration === "number" ? opt.duration : - opt.duration in jQuery.fx.speeds ? jQuery.fx.speeds[opt.duration] : jQuery.fx.speeds._default; - - // normalize opt.queue - true/undefined/null -> "fx" - if (opt.queue == null || opt.queue === true) { - opt.queue = "fx"; - } - - // Queueing - opt.old = opt.complete; - - opt.complete = function () { - if (jQuery.isFunction(opt.old)) { - opt.old.call(this); - } - - if (opt.queue) { - jQuery.dequeue(this, opt.queue); - } - }; - - return opt; - }; - jQuery.style = function (elem, name, value, extra) { - - // Don't set styles on text and comment nodes - if (!elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style) { - return; - } - - // Make sure that we're working with the right name - var ret, type, hooks, - origName = jQuery.camelCase(name), - style = elem.style; - - name = jQuery.cssProps[origName] || (jQuery.cssProps[origName] = vendorPropName(style, origName)); - - // gets hook for the prefixed version - // followed by the unprefixed version - hooks = jQuery.cssHooks[name] || jQuery.cssHooks[origName]; - - // Check if we're setting a value - if (value !== undefined) { - type = typeof value; - - // convert relative number strings (+= or -=) to relative numbers. #7345 - if (type === "string" && (ret = rrelNum.exec(value))) { - value = (ret[1] + 1) * ret[2] + parseFloat(jQuery.css(elem, name)); - // Fixes bug #9237 - type = "number"; - } - - // Make sure that NaN and null values aren't set. See: #7116 - if (value == null || type === "number" && isNaN(value)) { - return; - } - - // If a number was passed in, add 'px' to the (except for certain CSS properties) - if (type === "number" && !jQuery.cssNumber[origName]) { - value += "px"; - } - - // Fixes #8908, it can be done more correctly by specifying setters in cssHooks, - // but it would mean to define eight (for every problematic property) identical functions - if (!jQuery.support.clearCloneStyle && value === "" && name.indexOf("background") === 0) { - style[name] = "inherit"; - } - - // If a hook was provided, use that value, otherwise just set the specified value - if (!hooks || !("set" in hooks) || (value = hooks.set(elem, value, extra)) !== undefined) { - style[name] = value; - } - - } else { - // If a hook was provided get the non-computed value from there - if (hooks && "get" in hooks && (ret = hooks.get(elem, false, extra)) !== undefined) { - return ret; - } - - // Otherwise just get the value from the style object - return style[name]; - } - }; - jQuery.support = { - "checkOn": true, - "optSelected": true, - "reliableMarginRight": true, - "boxSizingReliable": true, - "pixelPosition": false, - "noCloneChecked": true, - "optDisabled": true, - "radioValue": true, - "checkClone": true, - "focusinBubbles": false, - "clearCloneStyle": true, - "cors": true, - "ajax": true, - "boxSizing": true - }; - jQuery.swap = function (elem, options, callback, args) { - - var ret, name, - old = {}; - - // Remember the old values, and insert the new ones - for (name in options) { - old[name] = elem.style[name]; - elem.style[name] = options[name]; - } - - ret = callback.apply(elem, args || []); - - // Revert the old values - for (name in options) { - elem.style[name] = old[name]; - } - - return ret; - }; - jQuery.text = function (elem) { - - var node, - ret = "", - i = 0, - nodeType = elem.nodeType; - - if (!nodeType) { - // If no nodeType, this is expected to be an array - for (; (node = elem[i]) ; i++) { - // Do not traverse comment nodes - ret += getText(node); - } - } else if (nodeType === 1 || nodeType === 9 || nodeType === 11) { - // Use textContent for elements - // innerText usage removed for consistency of new lines (see #11153) - if (typeof elem.textContent === "string") { - return elem.textContent; - } else { - // Traverse its children - for (elem = elem.firstChild; elem; elem = elem.nextSibling) { - ret += getText(elem); - } - } - } else if (nodeType === 3 || nodeType === 4) { - return elem.nodeValue; - } - // Do not include comment or processing instruction nodes - - return ret; - }; - jQuery.trim = function (text) { - /// - /// Remove the whitespace from the beginning and end of a string. - /// - /// - /// The string to trim. - /// - /// - - return text == null ? "" : core_trim.call(text); - }; - jQuery.type = function (obj) { - /// - /// Determine the internal JavaScript [[Class]] of an object. - /// - /// - /// Object to get the internal JavaScript [[Class]] of. - /// - /// - - if (obj == null) { - return String(obj); - } - // Support: Safari <= 5.1 (functionish RegExp) - return typeof obj === "object" || typeof obj === "function" ? - class2type[core_toString.call(obj)] || "object" : - typeof obj; - }; - jQuery.unique = function (results) { - /// - /// Sorts an array of DOM elements, in place, with the duplicates removed. Note that this only works on arrays of DOM elements, not strings or numbers. - /// - /// - /// The Array of DOM elements. - /// - /// - - var elem, - duplicates = [], - j = 0, - i = 0; - - // Unless we *know* we can detect duplicates, assume their presence - hasDuplicate = !support.detectDuplicates; - sortInput = !support.sortStable && results.slice(0); - results.sort(sortOrder); - - if (hasDuplicate) { - while ((elem = results[i++])) { - if (elem === results[i]) { - j = duplicates.push(i); - } - } - while (j--) { - results.splice(duplicates[j], 1); - } - } - - return results; - }; - jQuery.valHooks = { - "option": {}, - "select": {}, - "radio": {}, - "checkbox": {} - }; - jQuery.when = function (subordinate /* , ..., subordinateN */) { - /// - /// Provides a way to execute callback functions based on one or more objects, usually Deferred objects that represent asynchronous events. - /// - /// - /// One or more Deferred objects, or plain JavaScript objects. - /// - /// - - var i = 0, - resolveValues = core_slice.call(arguments), - length = resolveValues.length, - - // the count of uncompleted subordinates - remaining = length !== 1 || (subordinate && jQuery.isFunction(subordinate.promise)) ? length : 0, - - // the master Deferred. If resolveValues consist of only a single Deferred, just use that. - deferred = remaining === 1 ? subordinate : jQuery.Deferred(), - - // Update function for both resolve and progress values - updateFunc = function (i, contexts, values) { - return function (value) { - contexts[i] = this; - values[i] = arguments.length > 1 ? core_slice.call(arguments) : value; - if (values === progressValues) { - deferred.notifyWith(contexts, values); - } else if (!(--remaining)) { - deferred.resolveWith(contexts, values); - } - }; - }, - - progressValues, progressContexts, resolveContexts; - - // add listeners to Deferred subordinates; treat others as resolved - if (length > 1) { - progressValues = new Array(length); - progressContexts = new Array(length); - resolveContexts = new Array(length); - for (; i < length; i++) { - if (resolveValues[i] && jQuery.isFunction(resolveValues[i].promise)) { - resolveValues[i].promise() - .done(updateFunc(i, resolveContexts, resolveValues)) - .fail(deferred.reject) - .progress(updateFunc(i, progressContexts, progressValues)); - } else { - --remaining; - } - } - } - - // if we're not waiting on anything, resolve the master - if (!remaining) { - deferred.resolveWith(resolveContexts, resolveValues); - } - - return deferred.promise(); - }; - jQuery.Event.prototype.isDefaultPrevented = function returnFalse() { - /// - /// Returns whether event.preventDefault() was ever called on this event object. - /// - /// - - return false; - }; - jQuery.Event.prototype.isImmediatePropagationStopped = function returnFalse() { - /// - /// Returns whether event.stopImmediatePropagation() was ever called on this event object. - /// - /// - - return false; - }; - jQuery.Event.prototype.isPropagationStopped = function returnFalse() { - /// - /// Returns whether event.stopPropagation() was ever called on this event object. - /// - /// - - return false; - }; - jQuery.Event.prototype.preventDefault = function () { - /// - /// If this method is called, the default action of the event will not be triggered. - /// - /// - - var e = this.originalEvent; - - this.isDefaultPrevented = returnTrue; - - if (e && e.preventDefault) { - e.preventDefault(); - } - }; - jQuery.Event.prototype.stopImmediatePropagation = function () { - /// - /// Keeps the rest of the handlers from being executed and prevents the event from bubbling up the DOM tree. - /// - - this.isImmediatePropagationStopped = returnTrue; - this.stopPropagation(); - }; - jQuery.Event.prototype.stopPropagation = function () { - /// - /// Prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event. - /// - - var e = this.originalEvent; - - this.isPropagationStopped = returnTrue; - - if (e && e.stopPropagation) { - e.stopPropagation(); - } - }; - jQuery.prototype.add = function (selector, context) { - /// - /// Add elements to the set of matched elements. - /// 1 - add(selector) - /// 2 - add(elements) - /// 3 - add(html) - /// 4 - add(jQuery object) - /// 5 - add(selector, context) - /// - /// - /// A string representing a selector expression to find additional elements to add to the set of matched elements. - /// - /// - /// The point in the document at which the selector should begin matching; similar to the context argument of the $(selector, context) method. - /// - /// - - var set = typeof selector === "string" ? - jQuery(selector, context) : - jQuery.makeArray(selector && selector.nodeType ? [selector] : selector), - all = jQuery.merge(this.get(), set); - - return this.pushStack(jQuery.unique(all)); - }; - jQuery.prototype.addBack = function (selector) { - /// - /// Add the previous set of elements on the stack to the current set, optionally filtered by a selector. - /// - /// - /// A string containing a selector expression to match the current set of elements against. - /// - /// - - return this.add(selector == null ? - this.prevObject : this.prevObject.filter(selector) - ); - }; - jQuery.prototype.addClass = function (value) { - /// - /// Adds the specified class(es) to each of the set of matched elements. - /// 1 - addClass(className) - /// 2 - addClass(function(index, currentClass)) - /// - /// - /// One or more space-separated classes to be added to the class attribute of each matched element. - /// - /// - - var classes, elem, cur, clazz, j, - i = 0, - len = this.length, - proceed = typeof value === "string" && value; - - if (jQuery.isFunction(value)) { - return this.each(function (j) { - jQuery(this).addClass(value.call(this, j, this.className)); - }); - } - - if (proceed) { - // The disjunction here is for better compressibility (see removeClass) - classes = (value || "").match(core_rnotwhite) || []; - - for (; i < len; i++) { - elem = this[i]; - cur = elem.nodeType === 1 && (elem.className ? - (" " + elem.className + " ").replace(rclass, " ") : - " " - ); - - if (cur) { - j = 0; - while ((clazz = classes[j++])) { - if (cur.indexOf(" " + clazz + " ") < 0) { - cur += clazz + " "; - } - } - elem.className = jQuery.trim(cur); - - } - } - } - - return this; - }; - jQuery.prototype.after = function () { - /// - /// Insert content, specified by the parameter, after each element in the set of matched elements. - /// 1 - after(content, content) - /// 2 - after(function(index)) - /// - /// - /// HTML string, DOM element, or jQuery object to insert after each element in the set of matched elements. - /// - /// - /// One or more additional DOM elements, arrays of elements, HTML strings, or jQuery objects to insert after each element in the set of matched elements. - /// - /// - - return this.domManip(arguments, function (elem) { - if (this.parentNode) { - this.parentNode.insertBefore(elem, this.nextSibling); - } - }); - }; - jQuery.prototype.ajaxComplete = function (fn) { - /// - /// Register a handler to be called when Ajax requests complete. This is an AjaxEvent. - /// - /// - /// The function to be invoked. - /// - /// - - return this.on(type, fn); - }; - jQuery.prototype.ajaxError = function (fn) { - /// - /// Register a handler to be called when Ajax requests complete with an error. This is an Ajax Event. - /// - /// - /// The function to be invoked. - /// - /// - - return this.on(type, fn); - }; - jQuery.prototype.ajaxSend = function (fn) { - /// - /// Attach a function to be executed before an Ajax request is sent. This is an Ajax Event. - /// - /// - /// The function to be invoked. - /// - /// - - return this.on(type, fn); - }; - jQuery.prototype.ajaxStart = function (fn) { - /// - /// Register a handler to be called when the first Ajax request begins. This is an Ajax Event. - /// - /// - /// The function to be invoked. - /// - /// - - return this.on(type, fn); - }; - jQuery.prototype.ajaxStop = function (fn) { - /// - /// Register a handler to be called when all Ajax requests have completed. This is an Ajax Event. - /// - /// - /// The function to be invoked. - /// - /// - - return this.on(type, fn); - }; - jQuery.prototype.ajaxSuccess = function (fn) { - /// - /// Attach a function to be executed whenever an Ajax request completes successfully. This is an Ajax Event. - /// - /// - /// The function to be invoked. - /// - /// - - return this.on(type, fn); - }; - jQuery.prototype.andSelf = function (selector) { - /// - /// Add the previous set of elements on the stack to the current set. - /// - /// - - return this.add(selector == null ? - this.prevObject : this.prevObject.filter(selector) - ); - }; - jQuery.prototype.animate = function (prop, speed, easing, callback) { - /// - /// Perform a custom animation of a set of CSS properties. - /// 1 - animate(properties, duration, easing, complete) - /// 2 - animate(properties, options) - /// - /// - /// An object of CSS properties and values that the animation will move toward. - /// - /// - /// A string or number determining how long the animation will run. - /// - /// - /// A string indicating which easing function to use for the transition. - /// - /// - /// A function to call once the animation is complete. - /// - /// - - var empty = jQuery.isEmptyObject(prop), - optall = jQuery.speed(speed, easing, callback), - doAnimation = function () { - // Operate on a copy of prop so per-property easing won't be lost - var anim = Animation(this, jQuery.extend({}, prop), optall); - doAnimation.finish = function () { - anim.stop(true); - }; - // Empty animations, or finishing resolves immediately - if (empty || data_priv.get(this, "finish")) { - anim.stop(true); - } - }; - doAnimation.finish = doAnimation; - - return empty || optall.queue === false ? - this.each(doAnimation) : - this.queue(optall.queue, doAnimation); - }; - jQuery.prototype.append = function () { - /// - /// Insert content, specified by the parameter, to the end of each element in the set of matched elements. - /// 1 - append(content, content) - /// 2 - append(function(index, html)) - /// - /// - /// DOM element, HTML string, or jQuery object to insert at the end of each element in the set of matched elements. - /// - /// - /// One or more additional DOM elements, arrays of elements, HTML strings, or jQuery objects to insert at the end of each element in the set of matched elements. - /// - /// - - return this.domManip(arguments, function (elem) { - if (this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9) { - var target = manipulationTarget(this, elem); - target.appendChild(elem); - } - }); - }; - jQuery.prototype.appendTo = function (selector) { - /// - /// Insert every element in the set of matched elements to the end of the target. - /// - /// - /// A selector, element, HTML string, or jQuery object; the matched set of elements will be inserted at the end of the element(s) specified by this parameter. - /// - /// - - var elems, - ret = [], - insert = jQuery(selector), - last = insert.length - 1, - i = 0; - - for (; i <= last; i++) { - elems = i === last ? this : this.clone(true); - jQuery(insert[i])[original](elems); - - // Support: QtWebKit - // .get() because core_push.apply(_, arraylike) throws - core_push.apply(ret, elems.get()); - } - - return this.pushStack(ret); - }; - jQuery.prototype.attr = function (name, value) { - /// - /// 1: Get the value of an attribute for the first element in the set of matched elements. - /// 1.1 - attr(attributeName) - /// 2: Set one or more attributes for the set of matched elements. - /// 2.1 - attr(attributeName, value) - /// 2.2 - attr(attributes) - /// 2.3 - attr(attributeName, function(index, attr)) - /// - /// - /// The name of the attribute to set. - /// - /// - /// A value to set for the attribute. - /// - /// - - return jQuery.access(this, jQuery.attr, name, value, arguments.length > 1); - }; - jQuery.prototype.before = function () { - /// - /// Insert content, specified by the parameter, before each element in the set of matched elements. - /// 1 - before(content, content) - /// 2 - before(function) - /// - /// - /// HTML string, DOM element, or jQuery object to insert before each element in the set of matched elements. - /// - /// - /// One or more additional DOM elements, arrays of elements, HTML strings, or jQuery objects to insert before each element in the set of matched elements. - /// - /// - - return this.domManip(arguments, function (elem) { - if (this.parentNode) { - this.parentNode.insertBefore(elem, this); - } - }); - }; - jQuery.prototype.bind = function (types, data, fn) { - /// - /// Attach a handler to an event for the elements. - /// 1 - bind(eventType, eventData, handler(eventObject)) - /// 2 - bind(eventType, eventData, preventBubble) - /// 3 - bind(events) - /// - /// - /// A string containing one or more DOM event types, such as "click" or "submit," or custom event names. - /// - /// - /// An object containing data that will be passed to the event handler. - /// - /// - /// A function to execute each time the event is triggered. - /// - /// - - return this.on(types, null, data, fn); - }; - jQuery.prototype.blur = function (data, fn) { - /// - /// Bind an event handler to the "blur" JavaScript event, or trigger that event on an element. - /// 1 - blur(handler(eventObject)) - /// 2 - blur(eventData, handler(eventObject)) - /// 3 - blur() - /// - /// - /// An object containing data that will be passed to the event handler. - /// - /// - /// A function to execute each time the event is triggered. - /// - /// - - return arguments.length > 0 ? - this.on(name, null, data, fn) : - this.trigger(name); - }; - jQuery.prototype.change = function (data, fn) { - /// - /// Bind an event handler to the "change" JavaScript event, or trigger that event on an element. - /// 1 - change(handler(eventObject)) - /// 2 - change(eventData, handler(eventObject)) - /// 3 - change() - /// - /// - /// An object containing data that will be passed to the event handler. - /// - /// - /// A function to execute each time the event is triggered. - /// - /// - - return arguments.length > 0 ? - this.on(name, null, data, fn) : - this.trigger(name); - }; - jQuery.prototype.children = function (until, selector) { - /// - /// Get the children of each element in the set of matched elements, optionally filtered by a selector. - /// - /// - /// A string containing a selector expression to match elements against. - /// - /// - - var matched = jQuery.map(this, fn, until); - - if (name.slice(-5) !== "Until") { - selector = until; - } - - if (selector && typeof selector === "string") { - matched = jQuery.filter(selector, matched); - } - - if (this.length > 1) { - // Remove duplicates - if (!guaranteedUnique[name]) { - jQuery.unique(matched); - } - - // Reverse order for parents* and prev* - if (name[0] === "p") { - matched.reverse(); - } - } - - return this.pushStack(matched); - }; - jQuery.prototype.clearQueue = function (type) { - /// - /// Remove from the queue all items that have not yet been run. - /// - /// - /// A string containing the name of the queue. Defaults to fx, the standard effects queue. - /// - /// - - return this.queue(type || "fx", []); - }; - jQuery.prototype.click = function (data, fn) { - /// - /// Bind an event handler to the "click" JavaScript event, or trigger that event on an element. - /// 1 - click(handler(eventObject)) - /// 2 - click(eventData, handler(eventObject)) - /// 3 - click() - /// - /// - /// An object containing data that will be passed to the event handler. - /// - /// - /// A function to execute each time the event is triggered. - /// - /// - - return arguments.length > 0 ? - this.on(name, null, data, fn) : - this.trigger(name); - }; - jQuery.prototype.clone = function (dataAndEvents, deepDataAndEvents) { - /// - /// Create a deep copy of the set of matched elements. - /// 1 - clone(withDataAndEvents) - /// 2 - clone(withDataAndEvents, deepWithDataAndEvents) - /// - /// - /// A Boolean indicating whether event handlers and data should be copied along with the elements. The default value is false. *In jQuery 1.5.0 the default value was incorrectly true; it was changed back to false in 1.5.1 and up. - /// - /// - /// A Boolean indicating whether event handlers and data for all children of the cloned element should be copied. By default its value matches the first argument's value (which defaults to false). - /// - /// - - dataAndEvents = dataAndEvents == null ? false : dataAndEvents; - deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents; - - return this.map(function () { - return jQuery.clone(this, dataAndEvents, deepDataAndEvents); - }); - }; - jQuery.prototype.closest = function (selectors, context) { - /// - /// 1: For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree. - /// 1.1 - closest(selector) - /// 1.2 - closest(selector, context) - /// 1.3 - closest(jQuery object) - /// 1.4 - closest(element) - /// 2: Get an array of all the elements and selectors matched against the current element up through the DOM tree. - /// 2.1 - closest(selectors, context) - /// - /// - /// A string containing a selector expression to match elements against. - /// - /// - /// A DOM element within which a matching element may be found. If no context is passed in then the context of the jQuery set will be used instead. - /// - /// - - var cur, - i = 0, - l = this.length, - matched = [], - pos = (rneedsContext.test(selectors) || typeof selectors !== "string") ? - jQuery(selectors, context || this.context) : - 0; - - for (; i < l; i++) { - for (cur = this[i]; cur && cur !== context; cur = cur.parentNode) { - // Always skip document fragments - if (cur.nodeType < 11 && (pos ? - pos.index(cur) > -1 : - - // Don't pass non-elements to Sizzle - cur.nodeType === 1 && - jQuery.find.matchesSelector(cur, selectors))) { - - cur = matched.push(cur); - break; - } - } - } - - return this.pushStack(matched.length > 1 ? jQuery.unique(matched) : matched); - }; - jQuery.prototype.constructor = function (selector, context) { - - // The jQuery object is actually just the init constructor 'enhanced' - return new jQuery.fn.init(selector, context, rootjQuery); - }; - jQuery.prototype.contents = function (until, selector) { - /// - /// Get the children of each element in the set of matched elements, including text and comment nodes. - /// - /// - - var matched = jQuery.map(this, fn, until); - - if (name.slice(-5) !== "Until") { - selector = until; - } - - if (selector && typeof selector === "string") { - matched = jQuery.filter(selector, matched); - } - - if (this.length > 1) { - // Remove duplicates - if (!guaranteedUnique[name]) { - jQuery.unique(matched); - } - - // Reverse order for parents* and prev* - if (name[0] === "p") { - matched.reverse(); - } - } - - return this.pushStack(matched); - }; - jQuery.prototype.contextmenu = function (data, fn) { - - return arguments.length > 0 ? - this.on(name, null, data, fn) : - this.trigger(name); - }; - jQuery.prototype.css = function (name, value) { - /// - /// 1: Get the value of style properties for the first element in the set of matched elements. - /// 1.1 - css(propertyName) - /// 1.2 - css(propertyNames) - /// 2: Set one or more CSS properties for the set of matched elements. - /// 2.1 - css(propertyName, value) - /// 2.2 - css(propertyName, function(index, value)) - /// 2.3 - css(properties) - /// - /// - /// A CSS property name. - /// - /// - /// A value to set for the property. - /// - /// - - return jQuery.access(this, function (elem, name, value) { - var styles, len, - map = {}, - i = 0; - - if (jQuery.isArray(name)) { - styles = getStyles(elem); - len = name.length; - - for (; i < len; i++) { - map[name[i]] = jQuery.css(elem, name[i], false, styles); - } - - return map; - } - - return value !== undefined ? - jQuery.style(elem, name, value) : - jQuery.css(elem, name); - }, name, value, arguments.length > 1); - }; - jQuery.prototype.data = function (key, value) { - /// - /// 1: Store arbitrary data associated with the matched elements. - /// 1.1 - data(key, value) - /// 1.2 - data(obj) - /// 2: Return the value at the named data store for the first element in the jQuery collection, as set by data(name, value) or by an HTML5 data-* attribute. - /// 2.1 - data(key) - /// 2.2 - data() - /// - /// - /// A string naming the piece of data to set. - /// - /// - /// The new data value; it can be any Javascript type including Array or Object. - /// - /// - - var attrs, name, - elem = this[0], - i = 0, - data = null; - - // Gets all values - if (key === undefined) { - if (this.length) { - data = data_user.get(elem); - - if (elem.nodeType === 1 && !data_priv.get(elem, "hasDataAttrs")) { - attrs = elem.attributes; - for (; i < attrs.length; i++) { - name = attrs[i].name; - - if (name.indexOf("data-") === 0) { - name = jQuery.camelCase(name.substring(5)); - dataAttr(elem, name, data[name]); - } - } - data_priv.set(elem, "hasDataAttrs", true); - } - } - - return data; - } - - // Sets multiple values - if (typeof key === "object") { - return this.each(function () { - data_user.set(this, key); - }); - } - - return jQuery.access(this, function (value) { - var data, - camelKey = jQuery.camelCase(key); - - // The calling jQuery object (element matches) is not empty - // (and therefore has an element appears at this[ 0 ]) and the - // `value` parameter was not undefined. An empty jQuery object - // will result in `undefined` for elem = this[ 0 ] which will - // throw an exception if an attempt to read a data cache is made. - if (elem && value === undefined) { - // Attempt to get data from the cache - // with the key as-is - data = data_user.get(elem, key); - if (data !== undefined) { - return data; - } - - // Attempt to get data from the cache - // with the key camelized - data = data_user.get(elem, camelKey); - if (data !== undefined) { - return data; - } - - // Attempt to "discover" the data in - // HTML5 custom data-* attrs - data = dataAttr(elem, camelKey, undefined); - if (data !== undefined) { - return data; - } - - // We tried really hard, but the data doesn't exist. - return; - } - - // Set the data... - this.each(function () { - // First, attempt to store a copy or reference of any - // data that might've been store with a camelCased key. - var data = data_user.get(this, camelKey); - - // For HTML5 data-* attribute interop, we have to - // store property names with dashes in a camelCase form. - // This might not apply to all properties...* - data_user.set(this, camelKey, value); - - // *... In the case of properties that might _actually_ - // have dashes, we need to also store a copy of that - // unchanged property. - if (key.indexOf("-") !== -1 && data !== undefined) { - data_user.set(this, key, value); - } - }); - }, null, value, arguments.length > 1, null, true); - }; - jQuery.prototype.dblclick = function (data, fn) { - /// - /// Bind an event handler to the "dblclick" JavaScript event, or trigger that event on an element. - /// 1 - dblclick(handler(eventObject)) - /// 2 - dblclick(eventData, handler(eventObject)) - /// 3 - dblclick() - /// - /// - /// An object containing data that will be passed to the event handler. - /// - /// - /// A function to execute each time the event is triggered. - /// - /// - - return arguments.length > 0 ? - this.on(name, null, data, fn) : - this.trigger(name); - }; - jQuery.prototype.delay = function (time, type) { - /// - /// Set a timer to delay execution of subsequent items in the queue. - /// - /// - /// An integer indicating the number of milliseconds to delay execution of the next item in the queue. - /// - /// - /// A string containing the name of the queue. Defaults to fx, the standard effects queue. - /// - /// - - time = jQuery.fx ? jQuery.fx.speeds[time] || time : time; - type = type || "fx"; - - return this.queue(type, function (next, hooks) { - var timeout = setTimeout(next, time); - hooks.stop = function () { - clearTimeout(timeout); - }; - }); - }; - jQuery.prototype.delegate = function (selector, types, data, fn) { - /// - /// Attach a handler to one or more events for all elements that match the selector, now or in the future, based on a specific set of root elements. - /// 1 - delegate(selector, eventType, handler(eventObject)) - /// 2 - delegate(selector, eventType, eventData, handler(eventObject)) - /// 3 - delegate(selector, events) - /// - /// - /// A selector to filter the elements that trigger the event. - /// - /// - /// A string containing one or more space-separated JavaScript event types, such as "click" or "keydown," or custom event names. - /// - /// - /// An object containing data that will be passed to the event handler. - /// - /// - /// A function to execute at the time the event is triggered. - /// - /// - - return this.on(types, selector, data, fn); - }; - jQuery.prototype.dequeue = function (type) { - /// - /// Execute the next function on the queue for the matched elements. - /// - /// - /// A string containing the name of the queue. Defaults to fx, the standard effects queue. - /// - /// - - return this.each(function () { - jQuery.dequeue(this, type); - }); - }; - jQuery.prototype.detach = function (selector) { - /// - /// Remove the set of matched elements from the DOM. - /// - /// - /// A selector expression that filters the set of matched elements to be removed. - /// - /// - - return this.remove(selector, true); - }; - jQuery.prototype.domManip = function (args, callback, allowIntersection) { - - - // Flatten any nested arrays - args = core_concat.apply([], args); - - var fragment, first, scripts, hasScripts, node, doc, - i = 0, - l = this.length, - set = this, - iNoClone = l - 1, - value = args[0], - isFunction = jQuery.isFunction(value); - - // We can't cloneNode fragments that contain checked, in WebKit - if (isFunction || !(l <= 1 || typeof value !== "string" || jQuery.support.checkClone || !rchecked.test(value))) { - return this.each(function (index) { - var self = set.eq(index); - if (isFunction) { - args[0] = value.call(this, index, self.html()); - } - self.domManip(args, callback, allowIntersection); - }); - } - - if (l) { - fragment = jQuery.buildFragment(args, this[0].ownerDocument, false, !allowIntersection && this); - first = fragment.firstChild; - - if (fragment.childNodes.length === 1) { - fragment = first; - } - - if (first) { - scripts = jQuery.map(getAll(fragment, "script"), disableScript); - hasScripts = scripts.length; - - // Use the original fragment for the last item instead of the first because it can end up - // being emptied incorrectly in certain situations (#8070). - for (; i < l; i++) { - node = fragment; - - if (i !== iNoClone) { - node = jQuery.clone(node, true, true); - - // Keep references to cloned scripts for later restoration - if (hasScripts) { - // Support: QtWebKit - // jQuery.merge because core_push.apply(_, arraylike) throws - jQuery.merge(scripts, getAll(node, "script")); - } - } - - callback.call(this[i], node, i); - } - - if (hasScripts) { - doc = scripts[scripts.length - 1].ownerDocument; - - // Reenable scripts - jQuery.map(scripts, restoreScript); - - // Evaluate executable scripts on first document insertion - for (i = 0; i < hasScripts; i++) { - node = scripts[i]; - if (rscriptType.test(node.type || "") && - !data_priv.access(node, "globalEval") && jQuery.contains(doc, node)) { - - if (node.src) { - // Hope ajax is available... - jQuery._evalUrl(node.src); - } else { - jQuery.globalEval(node.textContent.replace(rcleanScript, "")); - } - } - } - } - } - } - - return this; - }; - jQuery.prototype.each = function (callback, args) { - /// - /// Iterate over a jQuery object, executing a function for each matched element. - /// - /// - /// A function to execute for each matched element. - /// - /// - - return jQuery.each(this, callback, args); - }; - jQuery.prototype.empty = function () { - /// - /// Remove all child nodes of the set of matched elements from the DOM. - /// - /// - - var elem, - i = 0; - - for (; (elem = this[i]) != null; i++) { - if (elem.nodeType === 1) { - - // Prevent memory leaks - jQuery.cleanData(getAll(elem, false)); - - // Remove any remaining nodes - elem.textContent = ""; - } - } - - return this; - }; - jQuery.prototype.end = function () { - /// - /// End the most recent filtering operation in the current chain and return the set of matched elements to its previous state. - /// - /// - - return this.prevObject || this.constructor(null); - }; - jQuery.prototype.eq = function (i) { - /// - /// Reduce the set of matched elements to the one at the specified index. - /// 1 - eq(index) - /// 2 - eq(-index) - /// - /// - /// An integer indicating the 0-based position of the element. - /// - /// - - var len = this.length, - j = +i + (i < 0 ? len : 0); - return this.pushStack(j >= 0 && j < len ? [this[j]] : []); - }; - jQuery.prototype.error = function (data, fn) { - /// - /// Bind an event handler to the "error" JavaScript event. - /// 1 - error(handler(eventObject)) - /// 2 - error(eventData, handler(eventObject)) - /// - /// - /// An object containing data that will be passed to the event handler. - /// - /// - /// A function to execute each time the event is triggered. - /// - /// - - return arguments.length > 0 ? - this.on(name, null, data, fn) : - this.trigger(name); - }; - jQuery.prototype.extend = function () { - - var options, name, src, copy, copyIsArray, clone, - target = arguments[0] || {}, - i = 1, - length = arguments.length, - deep = false; - - // Handle a deep copy situation - if (typeof target === "boolean") { - deep = target; - target = arguments[1] || {}; - // skip the boolean and the target - i = 2; - } - - // Handle case when target is a string or something (possible in deep copy) - if (typeof target !== "object" && !jQuery.isFunction(target)) { - target = {}; - } - - // extend jQuery itself if only one argument is passed - if (length === i) { - target = this; - --i; - } - - for (; i < length; i++) { - // Only deal with non-null/undefined values - if ((options = arguments[i]) != null) { - // Extend the base object - for (name in options) { - src = target[name]; - copy = options[name]; - - // Prevent never-ending loop - if (target === copy) { - continue; - } - - // Recurse if we're merging plain objects or arrays - if (deep && copy && (jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)))) { - if (copyIsArray) { - copyIsArray = false; - clone = src && jQuery.isArray(src) ? src : []; - - } else { - clone = src && jQuery.isPlainObject(src) ? src : {}; - } - - // Never move original objects, clone them - target[name] = jQuery.extend(deep, clone, copy); - - // Don't bring in undefined values - } else if (copy !== undefined) { - target[name] = copy; - } - } - } - } - - // Return the modified object - return target; - }; - jQuery.prototype.fadeIn = function (speed, easing, callback) { - /// - /// Display the matched elements by fading them to opaque. - /// 1 - fadeIn(duration, complete) - /// 2 - fadeIn(options) - /// 3 - fadeIn(duration, easing, complete) - /// - /// - /// A string or number determining how long the animation will run. - /// - /// - /// A string indicating which easing function to use for the transition. - /// - /// - /// A function to call once the animation is complete. - /// - /// - - return this.animate(props, speed, easing, callback); - }; - jQuery.prototype.fadeOut = function (speed, easing, callback) { - /// - /// Hide the matched elements by fading them to transparent. - /// 1 - fadeOut(duration, complete) - /// 2 - fadeOut(options) - /// 3 - fadeOut(duration, easing, complete) - /// - /// - /// A string or number determining how long the animation will run. - /// - /// - /// A string indicating which easing function to use for the transition. - /// - /// - /// A function to call once the animation is complete. - /// - /// - - return this.animate(props, speed, easing, callback); - }; - jQuery.prototype.fadeTo = function (speed, to, easing, callback) { - /// - /// Adjust the opacity of the matched elements. - /// 1 - fadeTo(duration, opacity, complete) - /// 2 - fadeTo(duration, opacity, easing, complete) - /// - /// - /// A string or number determining how long the animation will run. - /// - /// - /// A number between 0 and 1 denoting the target opacity. - /// - /// - /// A string indicating which easing function to use for the transition. - /// - /// - /// A function to call once the animation is complete. - /// - /// - - - // show any hidden elements after setting opacity to 0 - return this.filter(isHidden).css("opacity", 0).show() - - // animate to the value specified - .end().animate({ opacity: to }, speed, easing, callback); - }; - jQuery.prototype.fadeToggle = function (speed, easing, callback) { - /// - /// Display or hide the matched elements by animating their opacity. - /// 1 - fadeToggle(duration, easing, complete) - /// 2 - fadeToggle(options) - /// - /// - /// A string or number determining how long the animation will run. - /// - /// - /// A string indicating which easing function to use for the transition. - /// - /// - /// A function to call once the animation is complete. - /// - /// - - return this.animate(props, speed, easing, callback); - }; - jQuery.prototype.filter = function (selector) { - /// - /// Reduce the set of matched elements to those that match the selector or pass the function's test. - /// 1 - filter(selector) - /// 2 - filter(function(index)) - /// 3 - filter(element) - /// 4 - filter(jQuery object) - /// - /// - /// A string containing a selector expression to match the current set of elements against. - /// - /// - - return this.pushStack(winnow(this, selector || [], false)); - }; - jQuery.prototype.find = function (selector) { - /// - /// Get the descendants of each element in the current set of matched elements, filtered by a selector, jQuery object, or element. - /// 1 - find(selector) - /// 2 - find(jQuery object) - /// 3 - find(element) - /// - /// - /// A string containing a selector expression to match elements against. - /// - /// - - var self, matched, i, - l = this.length; - - if (typeof selector !== "string") { - self = this; - return this.pushStack(jQuery(selector).filter(function () { - for (i = 0; i < l; i++) { - if (jQuery.contains(self[i], this)) { - return true; - } - } - })); - } - - matched = []; - for (i = 0; i < l; i++) { - jQuery.find(selector, this[i], matched); - } - - // Needed because $( selector, context ) becomes $( context ).find( selector ) - matched = this.pushStack(l > 1 ? jQuery.unique(matched) : matched); - matched.selector = (this.selector ? this.selector + " " : "") + selector; - return matched; - }; - jQuery.prototype.finish = function (type) { - /// - /// Stop the currently-running animation, remove all queued animations, and complete all animations for the matched elements. - /// - /// - /// The name of the queue in which to stop animations. - /// - /// - - if (type !== false) { - type = type || "fx"; - } - return this.each(function () { - var index, - data = data_priv.get(this), - queue = data[type + "queue"], - hooks = data[type + "queueHooks"], - timers = jQuery.timers, - length = queue ? queue.length : 0; - - // enable finishing flag on private data - data.finish = true; - - // empty the queue first - jQuery.queue(this, type, []); - - if (hooks && hooks.cur && hooks.cur.finish) { - hooks.cur.finish.call(this); - } - - // look for any active animations, and finish them - for (index = timers.length; index--;) { - if (timers[index].elem === this && timers[index].queue === type) { - timers[index].anim.stop(true); - timers.splice(index, 1); - } - } - - // look for any animations in the old queue and finish them - for (index = 0; index < length; index++) { - if (queue[index] && queue[index].finish) { - queue[index].finish.call(this); - } - } - - // turn off finishing flag - delete data.finish; - }); - }; - jQuery.prototype.first = function () { - /// - /// Reduce the set of matched elements to the first in the set. - /// - /// - - return this.eq(0); - }; - jQuery.prototype.focus = function (data, fn) { - /// - /// Bind an event handler to the "focus" JavaScript event, or trigger that event on an element. - /// 1 - focus(handler(eventObject)) - /// 2 - focus(eventData, handler(eventObject)) - /// 3 - focus() - /// - /// - /// An object containing data that will be passed to the event handler. - /// - /// - /// A function to execute each time the event is triggered. - /// - /// - - return arguments.length > 0 ? - this.on(name, null, data, fn) : - this.trigger(name); - }; - jQuery.prototype.focusin = function (data, fn) { - /// - /// Bind an event handler to the "focusin" event. - /// 1 - focusin(handler(eventObject)) - /// 2 - focusin(eventData, handler(eventObject)) - /// - /// - /// An object containing data that will be passed to the event handler. - /// - /// - /// A function to execute each time the event is triggered. - /// - /// - - return arguments.length > 0 ? - this.on(name, null, data, fn) : - this.trigger(name); - }; - jQuery.prototype.focusout = function (data, fn) { - /// - /// Bind an event handler to the "focusout" JavaScript event. - /// 1 - focusout(handler(eventObject)) - /// 2 - focusout(eventData, handler(eventObject)) - /// - /// - /// An object containing data that will be passed to the event handler. - /// - /// - /// A function to execute each time the event is triggered. - /// - /// - - return arguments.length > 0 ? - this.on(name, null, data, fn) : - this.trigger(name); - }; - jQuery.prototype.get = function (num) { - /// - /// Retrieve the DOM elements matched by the jQuery object. - /// - /// - /// A zero-based integer indicating which element to retrieve. - /// - /// - - return num == null ? - - // Return a 'clean' array - this.toArray() : - - // Return just the object - (num < 0 ? this[this.length + num] : this[num]); - }; - jQuery.prototype.has = function (target) { - /// - /// Reduce the set of matched elements to those that have a descendant that matches the selector or DOM element. - /// 1 - has(selector) - /// 2 - has(contained) - /// - /// - /// A string containing a selector expression to match elements against. - /// - /// - - var targets = jQuery(target, this), - l = targets.length; - - return this.filter(function () { - var i = 0; - for (; i < l; i++) { - if (jQuery.contains(this, targets[i])) { - return true; - } - } - }); - }; - jQuery.prototype.hasClass = function (selector) { - /// - /// Determine whether any of the matched elements are assigned the given class. - /// - /// - /// The class name to search for. - /// - /// - - var className = " " + selector + " ", - i = 0, - l = this.length; - for (; i < l; i++) { - if (this[i].nodeType === 1 && (" " + this[i].className + " ").replace(rclass, " ").indexOf(className) >= 0) { - return true; - } - } - - return false; - }; - jQuery.prototype.height = function (margin, value) { - /// - /// 1: Get the current computed height for the first element in the set of matched elements. - /// 1.1 - height() - /// 2: Set the CSS height of every matched element. - /// 2.1 - height(value) - /// 2.2 - height(function(index, height)) - /// - /// - /// An integer representing the number of pixels, or an integer with an optional unit of measure appended (as a string). - /// - /// - - var chainable = arguments.length && (defaultExtra || typeof margin !== "boolean"), - extra = defaultExtra || (margin === true || value === true ? "margin" : "border"); - - return jQuery.access(this, function (elem, type, value) { - var doc; - - if (jQuery.isWindow(elem)) { - // As of 5/8/2012 this will yield incorrect results for Mobile Safari, but there - // isn't a whole lot we can do. See pull request at this URL for discussion: - // https://github.com/jquery/jquery/pull/764 - return elem.document.documentElement["client" + name]; - } - - // Get document width or height - if (elem.nodeType === 9) { - doc = elem.documentElement; - - // Either scroll[Width/Height] or offset[Width/Height] or client[Width/Height], - // whichever is greatest - return Math.max( - elem.body["scroll" + name], doc["scroll" + name], - elem.body["offset" + name], doc["offset" + name], - doc["client" + name] - ); - } - - return value === undefined ? - // Get width or height on the element, requesting but not forcing parseFloat - jQuery.css(elem, type, extra) : - - // Set width or height on the element - jQuery.style(elem, type, value, extra); - }, type, chainable ? margin : undefined, chainable, null); - }; - jQuery.prototype.hide = function (speed, easing, callback) { - /// - /// Hide the matched elements. - /// 1 - hide() - /// 2 - hide(duration, complete) - /// 3 - hide(options) - /// 4 - hide(duration, easing, complete) - /// - /// - /// A string or number determining how long the animation will run. - /// - /// - /// A string indicating which easing function to use for the transition. - /// - /// - /// A function to call once the animation is complete. - /// - /// - - return speed == null || typeof speed === "boolean" ? - cssFn.apply(this, arguments) : - this.animate(genFx(name, true), speed, easing, callback); - }; - jQuery.prototype.hover = function (fnOver, fnOut) { - /// - /// 1: Bind two handlers to the matched elements, to be executed when the mouse pointer enters and leaves the elements. - /// 1.1 - hover(handlerIn(eventObject), handlerOut(eventObject)) - /// 2: Bind a single handler to the matched elements, to be executed when the mouse pointer enters or leaves the elements. - /// 2.1 - hover(handlerInOut(eventObject)) - /// - /// - /// A function to execute when the mouse pointer enters the element. - /// - /// - /// A function to execute when the mouse pointer leaves the element. - /// - /// - - return this.mouseenter(fnOver).mouseleave(fnOut || fnOver); - }; - jQuery.prototype.html = function (value) { - /// - /// 1: Get the HTML contents of the first element in the set of matched elements. - /// 1.1 - html() - /// 2: Set the HTML contents of each element in the set of matched elements. - /// 2.1 - html(htmlString) - /// 2.2 - html(function(index, oldhtml)) - /// - /// - /// A string of HTML to set as the content of each matched element. - /// - /// - - return jQuery.access(this, function (value) { - var elem = this[0] || {}, - i = 0, - l = this.length; - - if (value === undefined && elem.nodeType === 1) { - return elem.innerHTML; - } - - // See if we can take a shortcut and just use innerHTML - if (typeof value === "string" && !rnoInnerhtml.test(value) && - !wrapMap[(rtagName.exec(value) || ["", ""])[1].toLowerCase()]) { - - value = value.replace(rxhtmlTag, "<$1>"); - - try { - for (; i < l; i++) { - elem = this[i] || {}; - - // Remove element nodes and prevent memory leaks - if (elem.nodeType === 1) { - jQuery.cleanData(getAll(elem, false)); - elem.innerHTML = value; - } - } - - elem = 0; - - // If using innerHTML throws an exception, use the fallback method - } catch (e) { } - } - - if (elem) { - this.empty().append(value); - } - }, null, value, arguments.length); - }; - jQuery.prototype.index = function (elem) { - /// - /// Search for a given element from among the matched elements. - /// 1 - index() - /// 2 - index(selector) - /// 3 - index(element) - /// - /// - /// A selector representing a jQuery collection in which to look for an element. - /// - /// - - - // No argument, return index in parent - if (!elem) { - return (this[0] && this[0].parentNode) ? this.first().prevAll().length : -1; - } - - // index in selector - if (typeof elem === "string") { - return core_indexOf.call(jQuery(elem), this[0]); - } - - // Locate the position of the desired element - return core_indexOf.call(this, - - // If it receives a jQuery object, the first element is used - elem.jquery ? elem[0] : elem - ); - }; - jQuery.prototype.init = function (selector, context, rootjQuery) { - - var match, elem; - - // HANDLE: $(""), $(null), $(undefined), $(false) - if (!selector) { - return this; - } - - // Handle HTML strings - if (typeof selector === "string") { - if (selector.charAt(0) === "<" && selector.charAt(selector.length - 1) === ">" && selector.length >= 3) { - // Assume that strings that start and end with <> are HTML and skip the regex check - match = [null, selector, null]; - - } else { - match = rquickExpr.exec(selector); - } - - // Match html or make sure no context is specified for #id - if (match && (match[1] || !context)) { - - // HANDLE: $(html) -> $(array) - if (match[1]) { - context = context instanceof jQuery ? context[0] : context; - - // scripts is true for back-compat - jQuery.merge(this, jQuery.parseHTML( - match[1], - context && context.nodeType ? context.ownerDocument || context : document, - true - )); - - // HANDLE: $(html, props) - if (rsingleTag.test(match[1]) && jQuery.isPlainObject(context)) { - for (match in context) { - // Properties of context are called as methods if possible - if (jQuery.isFunction(this[match])) { - this[match](context[match]); - - // ...and otherwise set as attributes - } else { - this.attr(match, context[match]); - } - } - } - - return this; - - // HANDLE: $(#id) - } else { - elem = document.getElementById(match[2]); - - // Check parentNode to catch when Blackberry 4.6 returns - // nodes that are no longer in the document #6963 - if (elem && elem.parentNode) { - // Inject the element directly into the jQuery object - this.length = 1; - this[0] = elem; - } - - this.context = document; - this.selector = selector; - return this; - } - - // HANDLE: $(expr, $(...)) - } else if (!context || context.jquery) { - return (context || rootjQuery).find(selector); - - // HANDLE: $(expr, context) - // (which is just equivalent to: $(context).find(expr) - } else { - return this.constructor(context).find(selector); - } - - // HANDLE: $(DOMElement) - } else if (selector.nodeType) { - this.context = this[0] = selector; - this.length = 1; - return this; - - // HANDLE: $(function) - // Shortcut for document ready - } else if (jQuery.isFunction(selector)) { - return rootjQuery.ready(selector); - } - - if (selector.selector !== undefined) { - this.selector = selector.selector; - this.context = selector.context; - } - - return jQuery.makeArray(selector, this); - }; - jQuery.prototype.innerHeight = function (margin, value) { - /// - /// Get the current computed height for the first element in the set of matched elements, including padding but not border. - /// - /// - - var chainable = arguments.length && (defaultExtra || typeof margin !== "boolean"), - extra = defaultExtra || (margin === true || value === true ? "margin" : "border"); - - return jQuery.access(this, function (elem, type, value) { - var doc; - - if (jQuery.isWindow(elem)) { - // As of 5/8/2012 this will yield incorrect results for Mobile Safari, but there - // isn't a whole lot we can do. See pull request at this URL for discussion: - // https://github.com/jquery/jquery/pull/764 - return elem.document.documentElement["client" + name]; - } - - // Get document width or height - if (elem.nodeType === 9) { - doc = elem.documentElement; - - // Either scroll[Width/Height] or offset[Width/Height] or client[Width/Height], - // whichever is greatest - return Math.max( - elem.body["scroll" + name], doc["scroll" + name], - elem.body["offset" + name], doc["offset" + name], - doc["client" + name] - ); - } - - return value === undefined ? - // Get width or height on the element, requesting but not forcing parseFloat - jQuery.css(elem, type, extra) : - - // Set width or height on the element - jQuery.style(elem, type, value, extra); - }, type, chainable ? margin : undefined, chainable, null); - }; - jQuery.prototype.innerWidth = function (margin, value) { - /// - /// Get the current computed width for the first element in the set of matched elements, including padding but not border. - /// - /// - - var chainable = arguments.length && (defaultExtra || typeof margin !== "boolean"), - extra = defaultExtra || (margin === true || value === true ? "margin" : "border"); - - return jQuery.access(this, function (elem, type, value) { - var doc; - - if (jQuery.isWindow(elem)) { - // As of 5/8/2012 this will yield incorrect results for Mobile Safari, but there - // isn't a whole lot we can do. See pull request at this URL for discussion: - // https://github.com/jquery/jquery/pull/764 - return elem.document.documentElement["client" + name]; - } - - // Get document width or height - if (elem.nodeType === 9) { - doc = elem.documentElement; - - // Either scroll[Width/Height] or offset[Width/Height] or client[Width/Height], - // whichever is greatest - return Math.max( - elem.body["scroll" + name], doc["scroll" + name], - elem.body["offset" + name], doc["offset" + name], - doc["client" + name] - ); - } - - return value === undefined ? - // Get width or height on the element, requesting but not forcing parseFloat - jQuery.css(elem, type, extra) : - - // Set width or height on the element - jQuery.style(elem, type, value, extra); - }, type, chainable ? margin : undefined, chainable, null); - }; - jQuery.prototype.insertAfter = function (selector) { - /// - /// Insert every element in the set of matched elements after the target. - /// - /// - /// A selector, element, HTML string, or jQuery object; the matched set of elements will be inserted after the element(s) specified by this parameter. - /// - /// - - var elems, - ret = [], - insert = jQuery(selector), - last = insert.length - 1, - i = 0; - - for (; i <= last; i++) { - elems = i === last ? this : this.clone(true); - jQuery(insert[i])[original](elems); - - // Support: QtWebKit - // .get() because core_push.apply(_, arraylike) throws - core_push.apply(ret, elems.get()); - } - - return this.pushStack(ret); - }; - jQuery.prototype.insertBefore = function (selector) { - /// - /// Insert every element in the set of matched elements before the target. - /// - /// - /// A selector, element, HTML string, or jQuery object; the matched set of elements will be inserted before the element(s) specified by this parameter. - /// - /// - - var elems, - ret = [], - insert = jQuery(selector), - last = insert.length - 1, - i = 0; - - for (; i <= last; i++) { - elems = i === last ? this : this.clone(true); - jQuery(insert[i])[original](elems); - - // Support: QtWebKit - // .get() because core_push.apply(_, arraylike) throws - core_push.apply(ret, elems.get()); - } - - return this.pushStack(ret); - }; - jQuery.prototype.is = function (selector) { - /// - /// Check the current matched set of elements against a selector, element, or jQuery object and return true if at least one of these elements matches the given arguments. - /// 1 - is(selector) - /// 2 - is(function(index)) - /// 3 - is(jQuery object) - /// 4 - is(element) - /// - /// - /// A string containing a selector expression to match elements against. - /// - /// - - return !!selector && ( - typeof selector === "string" ? - // If this is a positional/relative selector, check membership in the returned set - // so $("p:first").is("p:last") won't return true for a doc with two "p". - rneedsContext.test(selector) ? - jQuery(selector, this.context).index(this[0]) >= 0 : - jQuery.filter(selector, this).length > 0 : - this.filter(selector).length > 0); - }; - jQuery.prototype.keydown = function (data, fn) { - /// - /// Bind an event handler to the "keydown" JavaScript event, or trigger that event on an element. - /// 1 - keydown(handler(eventObject)) - /// 2 - keydown(eventData, handler(eventObject)) - /// 3 - keydown() - /// - /// - /// An object containing data that will be passed to the event handler. - /// - /// - /// A function to execute each time the event is triggered. - /// - /// - - return arguments.length > 0 ? - this.on(name, null, data, fn) : - this.trigger(name); - }; - jQuery.prototype.keypress = function (data, fn) { - /// - /// Bind an event handler to the "keypress" JavaScript event, or trigger that event on an element. - /// 1 - keypress(handler(eventObject)) - /// 2 - keypress(eventData, handler(eventObject)) - /// 3 - keypress() - /// - /// - /// An object containing data that will be passed to the event handler. - /// - /// - /// A function to execute each time the event is triggered. - /// - /// - - return arguments.length > 0 ? - this.on(name, null, data, fn) : - this.trigger(name); - }; - jQuery.prototype.keyup = function (data, fn) { - /// - /// Bind an event handler to the "keyup" JavaScript event, or trigger that event on an element. - /// 1 - keyup(handler(eventObject)) - /// 2 - keyup(eventData, handler(eventObject)) - /// 3 - keyup() - /// - /// - /// An object containing data that will be passed to the event handler. - /// - /// - /// A function to execute each time the event is triggered. - /// - /// - - return arguments.length > 0 ? - this.on(name, null, data, fn) : - this.trigger(name); - }; - jQuery.prototype.last = function () { - /// - /// Reduce the set of matched elements to the final one in the set. - /// - /// - - return this.eq(-1); - }; - jQuery.prototype.length = 0; - jQuery.prototype.load = function (url, params, callback) { - /// - /// 1: Bind an event handler to the "load" JavaScript event. - /// 1.1 - load(handler(eventObject)) - /// 1.2 - load(eventData, handler(eventObject)) - /// 2: Load data from the server and place the returned HTML into the matched element. - /// 2.1 - load(url, data, complete(responseText, textStatus, XMLHttpRequest)) - /// - /// - /// A string containing the URL to which the request is sent. - /// - /// - /// A plain object or string that is sent to the server with the request. - /// - /// - /// A callback function that is executed when the request completes. - /// - /// - - if (typeof url !== "string" && _load) { - return _load.apply(this, arguments); - } - - var selector, type, response, - self = this, - off = url.indexOf(" "); - - if (off >= 0) { - selector = url.slice(off); - url = url.slice(0, off); - } - - // If it's a function - if (jQuery.isFunction(params)) { - - // We assume that it's the callback - callback = params; - params = undefined; - - // Otherwise, build a param string - } else if (params && typeof params === "object") { - type = "POST"; - } - - // If we have elements to modify, make the request - if (self.length > 0) { - jQuery.ajax({ - url: url, - - // if "type" variable is undefined, then "GET" method will be used - type: type, - dataType: "html", - data: params - }).done(function (responseText) { - - // Save response for use in complete callback - response = arguments; - - self.html(selector ? - - // If a selector was specified, locate the right elements in a dummy div - // Exclude scripts to avoid IE 'Permission Denied' errors - jQuery("
      ").append(jQuery.parseHTML(responseText)).find(selector) : - - // Otherwise use the full result - responseText); - - }).complete(callback && function (jqXHR, status) { - self.each(callback, response || [jqXHR.responseText, status, jqXHR]); - }); - } - - return this; - }; - jQuery.prototype.map = function (callback) { - /// - /// Pass each element in the current matched set through a function, producing a new jQuery object containing the return values. - /// - /// - /// A function object that will be invoked for each element in the current set. - /// - /// - - return this.pushStack(jQuery.map(this, function (elem, i) { - return callback.call(elem, i, elem); - })); - }; - jQuery.prototype.mousedown = function (data, fn) { - /// - /// Bind an event handler to the "mousedown" JavaScript event, or trigger that event on an element. - /// 1 - mousedown(handler(eventObject)) - /// 2 - mousedown(eventData, handler(eventObject)) - /// 3 - mousedown() - /// - /// - /// An object containing data that will be passed to the event handler. - /// - /// - /// A function to execute each time the event is triggered. - /// - /// - - return arguments.length > 0 ? - this.on(name, null, data, fn) : - this.trigger(name); - }; - jQuery.prototype.mouseenter = function (data, fn) { - /// - /// Bind an event handler to be fired when the mouse enters an element, or trigger that handler on an element. - /// 1 - mouseenter(handler(eventObject)) - /// 2 - mouseenter(eventData, handler(eventObject)) - /// 3 - mouseenter() - /// - /// - /// An object containing data that will be passed to the event handler. - /// - /// - /// A function to execute each time the event is triggered. - /// - /// - - return arguments.length > 0 ? - this.on(name, null, data, fn) : - this.trigger(name); - }; - jQuery.prototype.mouseleave = function (data, fn) { - /// - /// Bind an event handler to be fired when the mouse leaves an element, or trigger that handler on an element. - /// 1 - mouseleave(handler(eventObject)) - /// 2 - mouseleave(eventData, handler(eventObject)) - /// 3 - mouseleave() - /// - /// - /// An object containing data that will be passed to the event handler. - /// - /// - /// A function to execute each time the event is triggered. - /// - /// - - return arguments.length > 0 ? - this.on(name, null, data, fn) : - this.trigger(name); - }; - jQuery.prototype.mousemove = function (data, fn) { - /// - /// Bind an event handler to the "mousemove" JavaScript event, or trigger that event on an element. - /// 1 - mousemove(handler(eventObject)) - /// 2 - mousemove(eventData, handler(eventObject)) - /// 3 - mousemove() - /// - /// - /// An object containing data that will be passed to the event handler. - /// - /// - /// A function to execute each time the event is triggered. - /// - /// - - return arguments.length > 0 ? - this.on(name, null, data, fn) : - this.trigger(name); - }; - jQuery.prototype.mouseout = function (data, fn) { - /// - /// Bind an event handler to the "mouseout" JavaScript event, or trigger that event on an element. - /// 1 - mouseout(handler(eventObject)) - /// 2 - mouseout(eventData, handler(eventObject)) - /// 3 - mouseout() - /// - /// - /// An object containing data that will be passed to the event handler. - /// - /// - /// A function to execute each time the event is triggered. - /// - /// - - return arguments.length > 0 ? - this.on(name, null, data, fn) : - this.trigger(name); - }; - jQuery.prototype.mouseover = function (data, fn) { - /// - /// Bind an event handler to the "mouseover" JavaScript event, or trigger that event on an element. - /// 1 - mouseover(handler(eventObject)) - /// 2 - mouseover(eventData, handler(eventObject)) - /// 3 - mouseover() - /// - /// - /// An object containing data that will be passed to the event handler. - /// - /// - /// A function to execute each time the event is triggered. - /// - /// - - return arguments.length > 0 ? - this.on(name, null, data, fn) : - this.trigger(name); - }; - jQuery.prototype.mouseup = function (data, fn) { - /// - /// Bind an event handler to the "mouseup" JavaScript event, or trigger that event on an element. - /// 1 - mouseup(handler(eventObject)) - /// 2 - mouseup(eventData, handler(eventObject)) - /// 3 - mouseup() - /// - /// - /// An object containing data that will be passed to the event handler. - /// - /// - /// A function to execute each time the event is triggered. - /// - /// - - return arguments.length > 0 ? - this.on(name, null, data, fn) : - this.trigger(name); - }; - jQuery.prototype.next = function (until, selector) { - /// - /// Get the immediately following sibling of each element in the set of matched elements. If a selector is provided, it retrieves the next sibling only if it matches that selector. - /// - /// - /// A string containing a selector expression to match elements against. - /// - /// - - var matched = jQuery.map(this, fn, until); - - if (name.slice(-5) !== "Until") { - selector = until; - } - - if (selector && typeof selector === "string") { - matched = jQuery.filter(selector, matched); - } - - if (this.length > 1) { - // Remove duplicates - if (!guaranteedUnique[name]) { - jQuery.unique(matched); - } - - // Reverse order for parents* and prev* - if (name[0] === "p") { - matched.reverse(); - } - } - - return this.pushStack(matched); - }; - jQuery.prototype.nextAll = function (until, selector) { - /// - /// Get all following siblings of each element in the set of matched elements, optionally filtered by a selector. - /// - /// - /// A string containing a selector expression to match elements against. - /// - /// - - var matched = jQuery.map(this, fn, until); - - if (name.slice(-5) !== "Until") { - selector = until; - } - - if (selector && typeof selector === "string") { - matched = jQuery.filter(selector, matched); - } - - if (this.length > 1) { - // Remove duplicates - if (!guaranteedUnique[name]) { - jQuery.unique(matched); - } - - // Reverse order for parents* and prev* - if (name[0] === "p") { - matched.reverse(); - } - } - - return this.pushStack(matched); - }; - jQuery.prototype.nextUntil = function (until, selector) { - /// - /// Get all following siblings of each element up to but not including the element matched by the selector, DOM node, or jQuery object passed. - /// 1 - nextUntil(selector, filter) - /// 2 - nextUntil(element, filter) - /// - /// - /// A string containing a selector expression to indicate where to stop matching following sibling elements. - /// - /// - /// A string containing a selector expression to match elements against. - /// - /// - - var matched = jQuery.map(this, fn, until); - - if (name.slice(-5) !== "Until") { - selector = until; - } - - if (selector && typeof selector === "string") { - matched = jQuery.filter(selector, matched); - } - - if (this.length > 1) { - // Remove duplicates - if (!guaranteedUnique[name]) { - jQuery.unique(matched); - } - - // Reverse order for parents* and prev* - if (name[0] === "p") { - matched.reverse(); - } - } - - return this.pushStack(matched); - }; - jQuery.prototype.not = function (selector) { - /// - /// Remove elements from the set of matched elements. - /// 1 - not(selector) - /// 2 - not(elements) - /// 3 - not(function(index)) - /// 4 - not(jQuery object) - /// - /// - /// A string containing a selector expression to match elements against. - /// - /// - - return this.pushStack(winnow(this, selector || [], true)); - }; - jQuery.prototype.off = function (types, selector, fn) { - /// - /// Remove an event handler. - /// 1 - off(events, selector, handler(eventObject)) - /// 2 - off(events, selector) - /// - /// - /// One or more space-separated event types and optional namespaces, or just namespaces, such as "click", "keydown.myPlugin", or ".myPlugin". - /// - /// - /// A selector which should match the one originally passed to .on() when attaching event handlers. - /// - /// - /// A handler function previously attached for the event(s), or the special value false. - /// - /// - - var handleObj, type; - if (types && types.preventDefault && types.handleObj) { - // ( event ) dispatched jQuery.Event - handleObj = types.handleObj; - jQuery(types.delegateTarget).off( - handleObj.namespace ? handleObj.origType + "." + handleObj.namespace : handleObj.origType, - handleObj.selector, - handleObj.handler - ); - return this; - } - if (typeof types === "object") { - // ( types-object [, selector] ) - for (type in types) { - this.off(type, selector, types[type]); - } - return this; - } - if (selector === false || typeof selector === "function") { - // ( types [, fn] ) - fn = selector; - selector = undefined; - } - if (fn === false) { - fn = returnFalse; - } - return this.each(function () { - jQuery.event.remove(this, types, fn, selector); - }); - }; - jQuery.prototype.offset = function (options) { - /// - /// 1: Get the current coordinates of the first element in the set of matched elements, relative to the document. - /// 1.1 - offset() - /// 2: Set the current coordinates of every element in the set of matched elements, relative to the document. - /// 2.1 - offset(coordinates) - /// 2.2 - offset(function(index, coords)) - /// - /// - /// An object containing the properties top and left, which are integers indicating the new top and left coordinates for the elements. - /// - /// - - if (arguments.length) { - return options === undefined ? - this : - this.each(function (i) { - jQuery.offset.setOffset(this, options, i); - }); - } - - var docElem, win, - elem = this[0], - box = { top: 0, left: 0 }, - doc = elem && elem.ownerDocument; - - if (!doc) { - return; - } - - docElem = doc.documentElement; - - // Make sure it's not a disconnected DOM node - if (!jQuery.contains(docElem, elem)) { - return box; - } - - // If we don't have gBCR, just use 0,0 rather than error - // BlackBerry 5, iOS 3 (original iPhone) - if (typeof elem.getBoundingClientRect !== core_strundefined) { - box = elem.getBoundingClientRect(); - } - win = getWindow(doc); - return { - top: box.top + win.pageYOffset - docElem.clientTop, - left: box.left + win.pageXOffset - docElem.clientLeft - }; - }; - jQuery.prototype.offsetParent = function () { - /// - /// Get the closest ancestor element that is positioned. - /// - /// - - return this.map(function () { - var offsetParent = this.offsetParent || docElem; - - while (offsetParent && (!jQuery.nodeName(offsetParent, "html") && jQuery.css(offsetParent, "position") === "static")) { - offsetParent = offsetParent.offsetParent; - } - - return offsetParent || docElem; - }); - }; - jQuery.prototype.on = function (types, selector, data, fn, /*INTERNAL*/ one) { - /// - /// Attach an event handler function for one or more events to the selected elements. - /// 1 - on(events, selector, data, handler(eventObject)) - /// 2 - on(events, selector, data) - /// - /// - /// One or more space-separated event types and optional namespaces, such as "click" or "keydown.myPlugin". - /// - /// - /// A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element. - /// - /// - /// Data to be passed to the handler in event.data when an event is triggered. - /// - /// - /// A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. - /// - /// - - var origFn, type; - - // Types can be a map of types/handlers - if (typeof types === "object") { - // ( types-Object, selector, data ) - if (typeof selector !== "string") { - // ( types-Object, data ) - data = data || selector; - selector = undefined; - } - for (type in types) { - this.on(type, selector, data, types[type], one); - } - return this; - } - - if (data == null && fn == null) { - // ( types, fn ) - fn = selector; - data = selector = undefined; - } else if (fn == null) { - if (typeof selector === "string") { - // ( types, selector, fn ) - fn = data; - data = undefined; - } else { - // ( types, data, fn ) - fn = data; - data = selector; - selector = undefined; - } - } - if (fn === false) { - fn = returnFalse; - } else if (!fn) { - return this; - } - - if (one === 1) { - origFn = fn; - fn = function (event) { - // Can use an empty set, since event contains the info - jQuery().off(event); - return origFn.apply(this, arguments); - }; - // Use same guid so caller can remove using origFn - fn.guid = origFn.guid || (origFn.guid = jQuery.guid++); - } - return this.each(function () { - jQuery.event.add(this, types, fn, data, selector); - }); - }; - jQuery.prototype.one = function (types, selector, data, fn) { - /// - /// Attach a handler to an event for the elements. The handler is executed at most once per element. - /// 1 - one(events, data, handler(eventObject)) - /// 2 - one(events, selector, data, handler(eventObject)) - /// 3 - one(events, selector, data) - /// - /// - /// One or more space-separated event types and optional namespaces, such as "click" or "keydown.myPlugin". - /// - /// - /// A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element. - /// - /// - /// Data to be passed to the handler in event.data when an event is triggered. - /// - /// - /// A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. - /// - /// - - return this.on(types, selector, data, fn, 1); - }; - jQuery.prototype.outerHeight = function (margin, value) { - /// - /// Get the current computed height for the first element in the set of matched elements, including padding, border, and optionally margin. Returns an integer (without "px") representation of the value or null if called on an empty set of elements. - /// - /// - /// A Boolean indicating whether to include the element's margin in the calculation. - /// - /// - - var chainable = arguments.length && (defaultExtra || typeof margin !== "boolean"), - extra = defaultExtra || (margin === true || value === true ? "margin" : "border"); - - return jQuery.access(this, function (elem, type, value) { - var doc; - - if (jQuery.isWindow(elem)) { - // As of 5/8/2012 this will yield incorrect results for Mobile Safari, but there - // isn't a whole lot we can do. See pull request at this URL for discussion: - // https://github.com/jquery/jquery/pull/764 - return elem.document.documentElement["client" + name]; - } - - // Get document width or height - if (elem.nodeType === 9) { - doc = elem.documentElement; - - // Either scroll[Width/Height] or offset[Width/Height] or client[Width/Height], - // whichever is greatest - return Math.max( - elem.body["scroll" + name], doc["scroll" + name], - elem.body["offset" + name], doc["offset" + name], - doc["client" + name] - ); - } - - return value === undefined ? - // Get width or height on the element, requesting but not forcing parseFloat - jQuery.css(elem, type, extra) : - - // Set width or height on the element - jQuery.style(elem, type, value, extra); - }, type, chainable ? margin : undefined, chainable, null); - }; - jQuery.prototype.outerWidth = function (margin, value) { - /// - /// Get the current computed width for the first element in the set of matched elements, including padding and border. - /// - /// - /// A Boolean indicating whether to include the element's margin in the calculation. - /// - /// - - var chainable = arguments.length && (defaultExtra || typeof margin !== "boolean"), - extra = defaultExtra || (margin === true || value === true ? "margin" : "border"); - - return jQuery.access(this, function (elem, type, value) { - var doc; - - if (jQuery.isWindow(elem)) { - // As of 5/8/2012 this will yield incorrect results for Mobile Safari, but there - // isn't a whole lot we can do. See pull request at this URL for discussion: - // https://github.com/jquery/jquery/pull/764 - return elem.document.documentElement["client" + name]; - } - - // Get document width or height - if (elem.nodeType === 9) { - doc = elem.documentElement; - - // Either scroll[Width/Height] or offset[Width/Height] or client[Width/Height], - // whichever is greatest - return Math.max( - elem.body["scroll" + name], doc["scroll" + name], - elem.body["offset" + name], doc["offset" + name], - doc["client" + name] - ); - } - - return value === undefined ? - // Get width or height on the element, requesting but not forcing parseFloat - jQuery.css(elem, type, extra) : - - // Set width or height on the element - jQuery.style(elem, type, value, extra); - }, type, chainable ? margin : undefined, chainable, null); - }; - jQuery.prototype.parent = function (until, selector) { - /// - /// Get the parent of each element in the current set of matched elements, optionally filtered by a selector. - /// - /// - /// A string containing a selector expression to match elements against. - /// - /// - - var matched = jQuery.map(this, fn, until); - - if (name.slice(-5) !== "Until") { - selector = until; - } - - if (selector && typeof selector === "string") { - matched = jQuery.filter(selector, matched); - } - - if (this.length > 1) { - // Remove duplicates - if (!guaranteedUnique[name]) { - jQuery.unique(matched); - } - - // Reverse order for parents* and prev* - if (name[0] === "p") { - matched.reverse(); - } - } - - return this.pushStack(matched); - }; - jQuery.prototype.parents = function (until, selector) { - /// - /// Get the ancestors of each element in the current set of matched elements, optionally filtered by a selector. - /// - /// - /// A string containing a selector expression to match elements against. - /// - /// - - var matched = jQuery.map(this, fn, until); - - if (name.slice(-5) !== "Until") { - selector = until; - } - - if (selector && typeof selector === "string") { - matched = jQuery.filter(selector, matched); - } - - if (this.length > 1) { - // Remove duplicates - if (!guaranteedUnique[name]) { - jQuery.unique(matched); - } - - // Reverse order for parents* and prev* - if (name[0] === "p") { - matched.reverse(); - } - } - - return this.pushStack(matched); - }; - jQuery.prototype.parentsUntil = function (until, selector) { - /// - /// Get the ancestors of each element in the current set of matched elements, up to but not including the element matched by the selector, DOM node, or jQuery object. - /// 1 - parentsUntil(selector, filter) - /// 2 - parentsUntil(element, filter) - /// - /// - /// A string containing a selector expression to indicate where to stop matching ancestor elements. - /// - /// - /// A string containing a selector expression to match elements against. - /// - /// - - var matched = jQuery.map(this, fn, until); - - if (name.slice(-5) !== "Until") { - selector = until; - } - - if (selector && typeof selector === "string") { - matched = jQuery.filter(selector, matched); - } - - if (this.length > 1) { - // Remove duplicates - if (!guaranteedUnique[name]) { - jQuery.unique(matched); - } - - // Reverse order for parents* and prev* - if (name[0] === "p") { - matched.reverse(); - } - } - - return this.pushStack(matched); - }; - jQuery.prototype.position = function () { - /// - /// Get the current coordinates of the first element in the set of matched elements, relative to the offset parent. - /// - /// - - if (!this[0]) { - return; - } - - var offsetParent, offset, - elem = this[0], - parentOffset = { top: 0, left: 0 }; - - // Fixed elements are offset from window (parentOffset = {top:0, left: 0}, because it is it's only offset parent - if (jQuery.css(elem, "position") === "fixed") { - // We assume that getBoundingClientRect is available when computed position is fixed - offset = elem.getBoundingClientRect(); - - } else { - // Get *real* offsetParent - offsetParent = this.offsetParent(); - - // Get correct offsets - offset = this.offset(); - if (!jQuery.nodeName(offsetParent[0], "html")) { - parentOffset = offsetParent.offset(); - } - - // Add offsetParent borders - parentOffset.top += jQuery.css(offsetParent[0], "borderTopWidth", true); - parentOffset.left += jQuery.css(offsetParent[0], "borderLeftWidth", true); - } - - // Subtract parent offsets and element margins - return { - top: offset.top - parentOffset.top - jQuery.css(elem, "marginTop", true), - left: offset.left - parentOffset.left - jQuery.css(elem, "marginLeft", true) - }; - }; - jQuery.prototype.prepend = function () { - /// - /// Insert content, specified by the parameter, to the beginning of each element in the set of matched elements. - /// 1 - prepend(content, content) - /// 2 - prepend(function(index, html)) - /// - /// - /// DOM element, array of elements, HTML string, or jQuery object to insert at the beginning of each element in the set of matched elements. - /// - /// - /// One or more additional DOM elements, arrays of elements, HTML strings, or jQuery objects to insert at the beginning of each element in the set of matched elements. - /// - /// - - return this.domManip(arguments, function (elem) { - if (this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9) { - var target = manipulationTarget(this, elem); - target.insertBefore(elem, target.firstChild); - } - }); - }; - jQuery.prototype.prependTo = function (selector) { - /// - /// Insert every element in the set of matched elements to the beginning of the target. - /// - /// - /// A selector, element, HTML string, or jQuery object; the matched set of elements will be inserted at the beginning of the element(s) specified by this parameter. - /// - /// - - var elems, - ret = [], - insert = jQuery(selector), - last = insert.length - 1, - i = 0; - - for (; i <= last; i++) { - elems = i === last ? this : this.clone(true); - jQuery(insert[i])[original](elems); - - // Support: QtWebKit - // .get() because core_push.apply(_, arraylike) throws - core_push.apply(ret, elems.get()); - } - - return this.pushStack(ret); - }; - jQuery.prototype.prev = function (until, selector) { - /// - /// Get the immediately preceding sibling of each element in the set of matched elements, optionally filtered by a selector. - /// - /// - /// A string containing a selector expression to match elements against. - /// - /// - - var matched = jQuery.map(this, fn, until); - - if (name.slice(-5) !== "Until") { - selector = until; - } - - if (selector && typeof selector === "string") { - matched = jQuery.filter(selector, matched); - } - - if (this.length > 1) { - // Remove duplicates - if (!guaranteedUnique[name]) { - jQuery.unique(matched); - } - - // Reverse order for parents* and prev* - if (name[0] === "p") { - matched.reverse(); - } - } - - return this.pushStack(matched); - }; - jQuery.prototype.prevAll = function (until, selector) { - /// - /// Get all preceding siblings of each element in the set of matched elements, optionally filtered by a selector. - /// - /// - /// A string containing a selector expression to match elements against. - /// - /// - - var matched = jQuery.map(this, fn, until); - - if (name.slice(-5) !== "Until") { - selector = until; - } - - if (selector && typeof selector === "string") { - matched = jQuery.filter(selector, matched); - } - - if (this.length > 1) { - // Remove duplicates - if (!guaranteedUnique[name]) { - jQuery.unique(matched); - } - - // Reverse order for parents* and prev* - if (name[0] === "p") { - matched.reverse(); - } - } - - return this.pushStack(matched); - }; - jQuery.prototype.prevUntil = function (until, selector) { - /// - /// Get all preceding siblings of each element up to but not including the element matched by the selector, DOM node, or jQuery object. - /// 1 - prevUntil(selector, filter) - /// 2 - prevUntil(element, filter) - /// - /// - /// A string containing a selector expression to indicate where to stop matching preceding sibling elements. - /// - /// - /// A string containing a selector expression to match elements against. - /// - /// - - var matched = jQuery.map(this, fn, until); - - if (name.slice(-5) !== "Until") { - selector = until; - } - - if (selector && typeof selector === "string") { - matched = jQuery.filter(selector, matched); - } - - if (this.length > 1) { - // Remove duplicates - if (!guaranteedUnique[name]) { - jQuery.unique(matched); - } - - // Reverse order for parents* and prev* - if (name[0] === "p") { - matched.reverse(); - } - } - - return this.pushStack(matched); - }; - jQuery.prototype.promise = function (type, obj) { - /// - /// Return a Promise object to observe when all actions of a certain type bound to the collection, queued or not, have finished. - /// - /// - /// The type of queue that needs to be observed. - /// - /// - /// Object onto which the promise methods have to be attached - /// - /// - - var tmp, - count = 1, - defer = jQuery.Deferred(), - elements = this, - i = this.length, - resolve = function () { - if (!(--count)) { - defer.resolveWith(elements, [elements]); - } - }; - - if (typeof type !== "string") { - obj = type; - type = undefined; - } - type = type || "fx"; - - while (i--) { - tmp = data_priv.get(elements[i], type + "queueHooks"); - if (tmp && tmp.empty) { - count++; - tmp.empty.add(resolve); - } - } - resolve(); - return defer.promise(obj); - }; - jQuery.prototype.prop = function (name, value) { - /// - /// 1: Get the value of a property for the first element in the set of matched elements. - /// 1.1 - prop(propertyName) - /// 2: Set one or more properties for the set of matched elements. - /// 2.1 - prop(propertyName, value) - /// 2.2 - prop(properties) - /// 2.3 - prop(propertyName, function(index, oldPropertyValue)) - /// - /// - /// The name of the property to set. - /// - /// - /// A value to set for the property. - /// - /// - - return jQuery.access(this, jQuery.prop, name, value, arguments.length > 1); - }; - jQuery.prototype.pushStack = function (elems) { - /// - /// Add a collection of DOM elements onto the jQuery stack. - /// 1 - pushStack(elements) - /// 2 - pushStack(elements, name, arguments) - /// - /// - /// An array of elements to push onto the stack and make into a new jQuery object. - /// - /// - /// The name of a jQuery method that generated the array of elements. - /// - /// - /// The arguments that were passed in to the jQuery method (for serialization). - /// - /// - - - // Build a new jQuery matched element set - var ret = jQuery.merge(this.constructor(), elems); - - // Add the old object onto the stack (as a reference) - ret.prevObject = this; - ret.context = this.context; - - // Return the newly-formed element set - return ret; - }; - jQuery.prototype.queue = function (type, data) { - /// - /// 1: Show the queue of functions to be executed on the matched elements. - /// 1.1 - queue(queueName) - /// 2: Manipulate the queue of functions to be executed, once for each matched element. - /// 2.1 - queue(queueName, newQueue) - /// 2.2 - queue(queueName, callback( next )) - /// - /// - /// A string containing the name of the queue. Defaults to fx, the standard effects queue. - /// - /// - /// An array of functions to replace the current queue contents. - /// - /// - - var setter = 2; - - if (typeof type !== "string") { - data = type; - type = "fx"; - setter--; - } - - if (arguments.length < setter) { - return jQuery.queue(this[0], type); - } - - return data === undefined ? - this : - this.each(function () { - var queue = jQuery.queue(this, type, data); - - // ensure a hooks for this queue - jQuery._queueHooks(this, type); - - if (type === "fx" && queue[0] !== "inprogress") { - jQuery.dequeue(this, type); - } - }); - }; - jQuery.prototype.ready = function (fn) { - /// - /// Specify a function to execute when the DOM is fully loaded. - /// - /// - /// A function to execute after the DOM is ready. - /// - /// - - // Add the callback - jQuery.ready.promise().done(fn); - - return this; - }; - jQuery.prototype.remove = function (selector, keepData) { - /// - /// Remove the set of matched elements from the DOM. - /// - /// - /// A selector expression that filters the set of matched elements to be removed. - /// - /// - - var elem, - elems = selector ? jQuery.filter(selector, this) : this, - i = 0; - - for (; (elem = elems[i]) != null; i++) { - if (!keepData && elem.nodeType === 1) { - jQuery.cleanData(getAll(elem)); - } - - if (elem.parentNode) { - if (keepData && jQuery.contains(elem.ownerDocument, elem)) { - setGlobalEval(getAll(elem, "script")); - } - elem.parentNode.removeChild(elem); - } - } - - return this; - }; - jQuery.prototype.removeAttr = function (name) { - /// - /// Remove an attribute from each element in the set of matched elements. - /// - /// - /// An attribute to remove; as of version 1.7, it can be a space-separated list of attributes. - /// - /// - - return this.each(function () { - jQuery.removeAttr(this, name); - }); - }; - jQuery.prototype.removeClass = function (value) { - /// - /// Remove a single class, multiple classes, or all classes from each element in the set of matched elements. - /// 1 - removeClass(className) - /// 2 - removeClass(function(index, class)) - /// - /// - /// One or more space-separated classes to be removed from the class attribute of each matched element. - /// - /// - - var classes, elem, cur, clazz, j, - i = 0, - len = this.length, - proceed = arguments.length === 0 || typeof value === "string" && value; - - if (jQuery.isFunction(value)) { - return this.each(function (j) { - jQuery(this).removeClass(value.call(this, j, this.className)); - }); - } - if (proceed) { - classes = (value || "").match(core_rnotwhite) || []; - - for (; i < len; i++) { - elem = this[i]; - // This expression is here for better compressibility (see addClass) - cur = elem.nodeType === 1 && (elem.className ? - (" " + elem.className + " ").replace(rclass, " ") : - "" - ); - - if (cur) { - j = 0; - while ((clazz = classes[j++])) { - // Remove *all* instances - while (cur.indexOf(" " + clazz + " ") >= 0) { - cur = cur.replace(" " + clazz + " ", " "); - } - } - elem.className = value ? jQuery.trim(cur) : ""; - } - } - } - - return this; - }; - jQuery.prototype.removeData = function (key) { - /// - /// Remove a previously-stored piece of data. - /// 1 - removeData(name) - /// 2 - removeData(list) - /// - /// - /// A string naming the piece of data to delete. - /// - /// - - return this.each(function () { - data_user.remove(this, key); - }); - }; - jQuery.prototype.removeProp = function (name) { - /// - /// Remove a property for the set of matched elements. - /// - /// - /// The name of the property to remove. - /// - /// - - return this.each(function () { - delete this[jQuery.propFix[name] || name]; - }); - }; - jQuery.prototype.replaceAll = function (selector) { - /// - /// Replace each target element with the set of matched elements. - /// - /// - /// A selector string, jQuery object, or DOM element reference indicating which element(s) to replace. - /// - /// - - var elems, - ret = [], - insert = jQuery(selector), - last = insert.length - 1, - i = 0; - - for (; i <= last; i++) { - elems = i === last ? this : this.clone(true); - jQuery(insert[i])[original](elems); - - // Support: QtWebKit - // .get() because core_push.apply(_, arraylike) throws - core_push.apply(ret, elems.get()); - } - - return this.pushStack(ret); - }; - jQuery.prototype.replaceWith = function () { - /// - /// Replace each element in the set of matched elements with the provided new content and return the set of elements that was removed. - /// 1 - replaceWith(newContent) - /// 2 - replaceWith(function) - /// - /// - /// The content to insert. May be an HTML string, DOM element, or jQuery object. - /// - /// - - var - // Snapshot the DOM in case .domManip sweeps something relevant into its fragment - args = jQuery.map(this, function (elem) { - return [elem.nextSibling, elem.parentNode]; - }), - i = 0; - - // Make the changes, replacing each context element with the new content - this.domManip(arguments, function (elem) { - var next = args[i++], - parent = args[i++]; - - if (parent) { - jQuery(this).remove(); - parent.insertBefore(elem, next); - } - // Allow new content to include elements from the context set - }, true); - - // Force removal if there was no new content (e.g., from empty arguments) - return i ? this : this.remove(); - }; - jQuery.prototype.resize = function (data, fn) { - /// - /// Bind an event handler to the "resize" JavaScript event, or trigger that event on an element. - /// 1 - resize(handler(eventObject)) - /// 2 - resize(eventData, handler(eventObject)) - /// 3 - resize() - /// - /// - /// An object containing data that will be passed to the event handler. - /// - /// - /// A function to execute each time the event is triggered. - /// - /// - - return arguments.length > 0 ? - this.on(name, null, data, fn) : - this.trigger(name); - }; - jQuery.prototype.scroll = function (data, fn) { - /// - /// Bind an event handler to the "scroll" JavaScript event, or trigger that event on an element. - /// 1 - scroll(handler(eventObject)) - /// 2 - scroll(eventData, handler(eventObject)) - /// 3 - scroll() - /// - /// - /// An object containing data that will be passed to the event handler. - /// - /// - /// A function to execute each time the event is triggered. - /// - /// - - return arguments.length > 0 ? - this.on(name, null, data, fn) : - this.trigger(name); - }; - jQuery.prototype.scrollLeft = function (val) { - /// - /// 1: Get the current horizontal position of the scroll bar for the first element in the set of matched elements. - /// 1.1 - scrollLeft() - /// 2: Set the current horizontal position of the scroll bar for each of the set of matched elements. - /// 2.1 - scrollLeft(value) - /// - /// - /// An integer indicating the new position to set the scroll bar to. - /// - /// - - return jQuery.access(this, function (elem, method, val) { - var win = getWindow(elem); - - if (val === undefined) { - return win ? win[prop] : elem[method]; - } - - if (win) { - win.scrollTo( - !top ? val : window.pageXOffset, - top ? val : window.pageYOffset - ); - - } else { - elem[method] = val; - } - }, method, val, arguments.length, null); - }; - jQuery.prototype.scrollTop = function (val) { - /// - /// 1: Get the current vertical position of the scroll bar for the first element in the set of matched elements or set the vertical position of the scroll bar for every matched element. - /// 1.1 - scrollTop() - /// 2: Set the current vertical position of the scroll bar for each of the set of matched elements. - /// 2.1 - scrollTop(value) - /// - /// - /// An integer indicating the new position to set the scroll bar to. - /// - /// - - return jQuery.access(this, function (elem, method, val) { - var win = getWindow(elem); - - if (val === undefined) { - return win ? win[prop] : elem[method]; - } - - if (win) { - win.scrollTo( - !top ? val : window.pageXOffset, - top ? val : window.pageYOffset - ); - - } else { - elem[method] = val; - } - }, method, val, arguments.length, null); - }; - jQuery.prototype.select = function (data, fn) { - /// - /// Bind an event handler to the "select" JavaScript event, or trigger that event on an element. - /// 1 - select(handler(eventObject)) - /// 2 - select(eventData, handler(eventObject)) - /// 3 - select() - /// - /// - /// An object containing data that will be passed to the event handler. - /// - /// - /// A function to execute each time the event is triggered. - /// - /// - - return arguments.length > 0 ? - this.on(name, null, data, fn) : - this.trigger(name); - }; - jQuery.prototype.serialize = function () { - /// - /// Encode a set of form elements as a string for submission. - /// - /// - - return jQuery.param(this.serializeArray()); - }; - jQuery.prototype.serializeArray = function () { - /// - /// Encode a set of form elements as an array of names and values. - /// - /// - - return this.map(function () { - // Can add propHook for "elements" to filter or add form elements - var elements = jQuery.prop(this, "elements"); - return elements ? jQuery.makeArray(elements) : this; - }) - .filter(function () { - var type = this.type; - // Use .is(":disabled") so that fieldset[disabled] works - return this.name && !jQuery(this).is(":disabled") && - rsubmittable.test(this.nodeName) && !rsubmitterTypes.test(type) && - (this.checked || !manipulation_rcheckableType.test(type)); - }) - .map(function (i, elem) { - var val = jQuery(this).val(); - - return val == null ? - null : - jQuery.isArray(val) ? - jQuery.map(val, function (val) { - return { name: elem.name, value: val.replace(rCRLF, "\r\n") }; - }) : - { name: elem.name, value: val.replace(rCRLF, "\r\n") }; - }).get(); - }; - jQuery.prototype.show = function (speed, easing, callback) { - /// - /// Display the matched elements. - /// 1 - show() - /// 2 - show(duration, complete) - /// 3 - show(options) - /// 4 - show(duration, easing, complete) - /// - /// - /// A string or number determining how long the animation will run. - /// - /// - /// A string indicating which easing function to use for the transition. - /// - /// - /// A function to call once the animation is complete. - /// - /// - - return speed == null || typeof speed === "boolean" ? - cssFn.apply(this, arguments) : - this.animate(genFx(name, true), speed, easing, callback); - }; - jQuery.prototype.siblings = function (until, selector) { - /// - /// Get the siblings of each element in the set of matched elements, optionally filtered by a selector. - /// - /// - /// A string containing a selector expression to match elements against. - /// - /// - - var matched = jQuery.map(this, fn, until); - - if (name.slice(-5) !== "Until") { - selector = until; - } - - if (selector && typeof selector === "string") { - matched = jQuery.filter(selector, matched); - } - - if (this.length > 1) { - // Remove duplicates - if (!guaranteedUnique[name]) { - jQuery.unique(matched); - } - - // Reverse order for parents* and prev* - if (name[0] === "p") { - matched.reverse(); - } - } - - return this.pushStack(matched); - }; - jQuery.prototype.size = function () { - /// - /// Return the number of elements in the jQuery object. - /// - /// - - return this.length; - }; - jQuery.prototype.slice = function () { - /// - /// Reduce the set of matched elements to a subset specified by a range of indices. - /// - /// - /// An integer indicating the 0-based position at which the elements begin to be selected. If negative, it indicates an offset from the end of the set. - /// - /// - /// An integer indicating the 0-based position at which the elements stop being selected. If negative, it indicates an offset from the end of the set. If omitted, the range continues until the end of the set. - /// - /// - - return this.pushStack(core_slice.apply(this, arguments)); - }; - jQuery.prototype.slideDown = function (speed, easing, callback) { - /// - /// Display the matched elements with a sliding motion. - /// 1 - slideDown(duration, complete) - /// 2 - slideDown(options) - /// 3 - slideDown(duration, easing, complete) - /// - /// - /// A string or number determining how long the animation will run. - /// - /// - /// A string indicating which easing function to use for the transition. - /// - /// - /// A function to call once the animation is complete. - /// - /// - - return this.animate(props, speed, easing, callback); - }; - jQuery.prototype.slideToggle = function (speed, easing, callback) { - /// - /// Display or hide the matched elements with a sliding motion. - /// 1 - slideToggle(duration, complete) - /// 2 - slideToggle(options) - /// 3 - slideToggle(duration, easing, complete) - /// - /// - /// A string or number determining how long the animation will run. - /// - /// - /// A string indicating which easing function to use for the transition. - /// - /// - /// A function to call once the animation is complete. - /// - /// - - return this.animate(props, speed, easing, callback); - }; - jQuery.prototype.slideUp = function (speed, easing, callback) { - /// - /// Hide the matched elements with a sliding motion. - /// 1 - slideUp(duration, complete) - /// 2 - slideUp(options) - /// 3 - slideUp(duration, easing, complete) - /// - /// - /// A string or number determining how long the animation will run. - /// - /// - /// A string indicating which easing function to use for the transition. - /// - /// - /// A function to call once the animation is complete. - /// - /// - - return this.animate(props, speed, easing, callback); - }; - jQuery.prototype.stop = function (type, clearQueue, gotoEnd) { - /// - /// Stop the currently-running animation on the matched elements. - /// 1 - stop(clearQueue, jumpToEnd) - /// 2 - stop(queue, clearQueue, jumpToEnd) - /// - /// - /// The name of the queue in which to stop animations. - /// - /// - /// A Boolean indicating whether to remove queued animation as well. Defaults to false. - /// - /// - /// A Boolean indicating whether to complete the current animation immediately. Defaults to false. - /// - /// - - var stopQueue = function (hooks) { - var stop = hooks.stop; - delete hooks.stop; - stop(gotoEnd); - }; - - if (typeof type !== "string") { - gotoEnd = clearQueue; - clearQueue = type; - type = undefined; - } - if (clearQueue && type !== false) { - this.queue(type || "fx", []); - } - - return this.each(function () { - var dequeue = true, - index = type != null && type + "queueHooks", - timers = jQuery.timers, - data = data_priv.get(this); - - if (index) { - if (data[index] && data[index].stop) { - stopQueue(data[index]); - } - } else { - for (index in data) { - if (data[index] && data[index].stop && rrun.test(index)) { - stopQueue(data[index]); - } - } - } - - for (index = timers.length; index--;) { - if (timers[index].elem === this && (type == null || timers[index].queue === type)) { - timers[index].anim.stop(gotoEnd); - dequeue = false; - timers.splice(index, 1); - } - } - - // start the next in the queue if the last step wasn't forced - // timers currently will call their complete callbacks, which will dequeue - // but only if they were gotoEnd - if (dequeue || !gotoEnd) { - jQuery.dequeue(this, type); - } - }); - }; - jQuery.prototype.submit = function (data, fn) { - /// - /// Bind an event handler to the "submit" JavaScript event, or trigger that event on an element. - /// 1 - submit(handler(eventObject)) - /// 2 - submit(eventData, handler(eventObject)) - /// 3 - submit() - /// - /// - /// An object containing data that will be passed to the event handler. - /// - /// - /// A function to execute each time the event is triggered. - /// - /// - - return arguments.length > 0 ? - this.on(name, null, data, fn) : - this.trigger(name); - }; - jQuery.prototype.text = function (value) { - /// - /// 1: Get the combined text contents of each element in the set of matched elements, including their descendants. - /// 1.1 - text() - /// 2: Set the content of each element in the set of matched elements to the specified text. - /// 2.1 - text(textString) - /// 2.2 - text(function(index, text)) - /// - /// - /// A string of text to set as the content of each matched element. - /// - /// - - return jQuery.access(this, function (value) { - return value === undefined ? - jQuery.text(this) : - this.empty().append((this[0] && this[0].ownerDocument || document).createTextNode(value)); - }, null, value, arguments.length); - }; - jQuery.prototype.toArray = function () { - /// - /// Retrieve all the DOM elements contained in the jQuery set, as an array. - /// - /// - - return core_slice.call(this); - }; - jQuery.prototype.toggle = function (speed, easing, callback) { - /// - /// 1: Bind two or more handlers to the matched elements, to be executed on alternate clicks. - /// 1.1 - toggle(handler(eventObject), handler(eventObject), handler(eventObject)) - /// 2: Display or hide the matched elements. - /// 2.1 - toggle(duration, complete) - /// 2.2 - toggle(options) - /// 2.3 - toggle(duration, easing, complete) - /// 2.4 - toggle(showOrHide) - /// - /// - /// A function to execute every even time the element is clicked. - /// - /// - /// A function to execute every odd time the element is clicked. - /// - /// - /// Additional handlers to cycle through after clicks. - /// - /// - - return speed == null || typeof speed === "boolean" ? - cssFn.apply(this, arguments) : - this.animate(genFx(name, true), speed, easing, callback); - }; - jQuery.prototype.toggleClass = function (value, stateVal) { - /// - /// Add or remove one or more classes from each element in the set of matched elements, depending on either the class's presence or the value of the switch argument. - /// 1 - toggleClass(className) - /// 2 - toggleClass(className, switch) - /// 3 - toggleClass(switch) - /// 4 - toggleClass(function(index, class, switch), switch) - /// - /// - /// One or more class names (separated by spaces) to be toggled for each element in the matched set. - /// - /// - /// A Boolean (not just truthy/falsy) value to determine whether the class should be added or removed. - /// - /// - - var type = typeof value, - isBool = typeof stateVal === "boolean"; - - if (jQuery.isFunction(value)) { - return this.each(function (i) { - jQuery(this).toggleClass(value.call(this, i, this.className, stateVal), stateVal); - }); - } - - return this.each(function () { - if (type === "string") { - // toggle individual class names - var className, - i = 0, - self = jQuery(this), - state = stateVal, - classNames = value.match(core_rnotwhite) || []; - - while ((className = classNames[i++])) { - // check each className given, space separated list - state = isBool ? state : !self.hasClass(className); - self[state ? "addClass" : "removeClass"](className); - } - - // Toggle whole class name - } else if (type === core_strundefined || type === "boolean") { - if (this.className) { - // store className if set - data_priv.set(this, "__className__", this.className); - } - - // If the element has a class name or if we're passed "false", - // then remove the whole classname (if there was one, the above saved it). - // Otherwise bring back whatever was previously saved (if anything), - // falling back to the empty string if nothing was stored. - this.className = this.className || value === false ? "" : data_priv.get(this, "__className__") || ""; - } - }); - }; - jQuery.prototype.trigger = function (type, data) { - /// - /// Execute all handlers and behaviors attached to the matched elements for the given event type. - /// 1 - trigger(eventType, extraParameters) - /// 2 - trigger(event, extraParameters) - /// - /// - /// A string containing a JavaScript event type, such as click or submit. - /// - /// - /// Additional parameters to pass along to the event handler. - /// - /// - - return this.each(function () { - jQuery.event.trigger(type, data, this); - }); - }; - jQuery.prototype.triggerHandler = function (type, data) { - /// - /// Execute all handlers attached to an element for an event. - /// - /// - /// A string containing a JavaScript event type, such as click or submit. - /// - /// - /// An array of additional parameters to pass along to the event handler. - /// - /// - - var elem = this[0]; - if (elem) { - return jQuery.event.trigger(type, data, elem, true); - } - }; - jQuery.prototype.unbind = function (types, fn) { - /// - /// Remove a previously-attached event handler from the elements. - /// 1 - unbind(eventType, handler(eventObject)) - /// 2 - unbind(eventType, false) - /// 3 - unbind(event) - /// - /// - /// A string containing a JavaScript event type, such as click or submit. - /// - /// - /// The function that is to be no longer executed. - /// - /// - - return this.off(types, null, fn); - }; - jQuery.prototype.undelegate = function (selector, types, fn) { - /// - /// Remove a handler from the event for all elements which match the current selector, based upon a specific set of root elements. - /// 1 - undelegate() - /// 2 - undelegate(selector, eventType) - /// 3 - undelegate(selector, eventType, handler(eventObject)) - /// 4 - undelegate(selector, events) - /// 5 - undelegate(namespace) - /// - /// - /// A selector which will be used to filter the event results. - /// - /// - /// A string containing a JavaScript event type, such as "click" or "keydown" - /// - /// - /// A function to execute at the time the event is triggered. - /// - /// - - // ( namespace ) or ( selector, types [, fn] ) - return arguments.length === 1 ? this.off(selector, "**") : this.off(types, selector || "**", fn); - }; - jQuery.prototype.unload = function (data, fn) { - /// - /// Bind an event handler to the "unload" JavaScript event. - /// 1 - unload(handler(eventObject)) - /// 2 - unload(eventData, handler(eventObject)) - /// - /// - /// A plain object of data that will be passed to the event handler. - /// - /// - /// A function to execute each time the event is triggered. - /// - /// - - return arguments.length > 0 ? - this.on(name, null, data, fn) : - this.trigger(name); - }; - jQuery.prototype.unwrap = function () { - /// - /// Remove the parents of the set of matched elements from the DOM, leaving the matched elements in their place. - /// - /// - - return this.parent().each(function () { - if (!jQuery.nodeName(this, "body")) { - jQuery(this).replaceWith(this.childNodes); - } - }).end(); - }; - jQuery.prototype.val = function (value) { - /// - /// 1: Get the current value of the first element in the set of matched elements. - /// 1.1 - val() - /// 2: Set the value of each element in the set of matched elements. - /// 2.1 - val(value) - /// 2.2 - val(function(index, value)) - /// - /// - /// A string of text or an array of strings corresponding to the value of each matched element to set as selected/checked. - /// - /// - - var hooks, ret, isFunction, - elem = this[0]; - - if (!arguments.length) { - if (elem) { - hooks = jQuery.valHooks[elem.type] || jQuery.valHooks[elem.nodeName.toLowerCase()]; - - if (hooks && "get" in hooks && (ret = hooks.get(elem, "value")) !== undefined) { - return ret; - } - - ret = elem.value; - - return typeof ret === "string" ? - // handle most common string cases - ret.replace(rreturn, "") : - // handle cases where value is null/undef or number - ret == null ? "" : ret; - } - - return; - } - - isFunction = jQuery.isFunction(value); - - return this.each(function (i) { - var val, - self = jQuery(this); - - if (this.nodeType !== 1) { - return; - } - - if (isFunction) { - val = value.call(this, i, self.val()); - } else { - val = value; - } - - // Treat null/undefined as ""; convert numbers to string - if (val == null) { - val = ""; - } else if (typeof val === "number") { - val += ""; - } else if (jQuery.isArray(val)) { - val = jQuery.map(val, function (value) { - return value == null ? "" : value + ""; - }); - } - - hooks = jQuery.valHooks[this.type] || jQuery.valHooks[this.nodeName.toLowerCase()]; - - // If set returns undefined, fall back to normal setting - if (!hooks || !("set" in hooks) || hooks.set(this, val, "value") === undefined) { - this.value = val; - } - }); - }; - jQuery.prototype.width = function (margin, value) { - /// - /// 1: Get the current computed width for the first element in the set of matched elements. - /// 1.1 - width() - /// 2: Set the CSS width of each element in the set of matched elements. - /// 2.1 - width(value) - /// 2.2 - width(function(index, width)) - /// - /// - /// An integer representing the number of pixels, or an integer along with an optional unit of measure appended (as a string). - /// - /// - - var chainable = arguments.length && (defaultExtra || typeof margin !== "boolean"), - extra = defaultExtra || (margin === true || value === true ? "margin" : "border"); - - return jQuery.access(this, function (elem, type, value) { - var doc; - - if (jQuery.isWindow(elem)) { - // As of 5/8/2012 this will yield incorrect results for Mobile Safari, but there - // isn't a whole lot we can do. See pull request at this URL for discussion: - // https://github.com/jquery/jquery/pull/764 - return elem.document.documentElement["client" + name]; - } - - // Get document width or height - if (elem.nodeType === 9) { - doc = elem.documentElement; - - // Either scroll[Width/Height] or offset[Width/Height] or client[Width/Height], - // whichever is greatest - return Math.max( - elem.body["scroll" + name], doc["scroll" + name], - elem.body["offset" + name], doc["offset" + name], - doc["client" + name] - ); - } - - return value === undefined ? - // Get width or height on the element, requesting but not forcing parseFloat - jQuery.css(elem, type, extra) : - - // Set width or height on the element - jQuery.style(elem, type, value, extra); - }, type, chainable ? margin : undefined, chainable, null); - }; - jQuery.prototype.wrap = function (html) { - /// - /// Wrap an HTML structure around each element in the set of matched elements. - /// 1 - wrap(wrappingElement) - /// 2 - wrap(function(index)) - /// - /// - /// A selector, element, HTML string, or jQuery object specifying the structure to wrap around the matched elements. - /// - /// - - var isFunction = jQuery.isFunction(html); - - return this.each(function (i) { - jQuery(this).wrapAll(isFunction ? html.call(this, i) : html); - }); - }; - jQuery.prototype.wrapAll = function (html) { - /// - /// Wrap an HTML structure around all elements in the set of matched elements. - /// - /// - /// A selector, element, HTML string, or jQuery object specifying the structure to wrap around the matched elements. - /// - /// - - var wrap; - - if (jQuery.isFunction(html)) { - return this.each(function (i) { - jQuery(this).wrapAll(html.call(this, i)); - }); - } - - if (this[0]) { - - // The elements to wrap the target around - wrap = jQuery(html, this[0].ownerDocument).eq(0).clone(true); - - if (this[0].parentNode) { - wrap.insertBefore(this[0]); - } - - wrap.map(function () { - var elem = this; - - while (elem.firstElementChild) { - elem = elem.firstElementChild; - } - - return elem; - }).append(this); - } - - return this; - }; - jQuery.prototype.wrapInner = function (html) { - /// - /// Wrap an HTML structure around the content of each element in the set of matched elements. - /// 1 - wrapInner(wrappingElement) - /// 2 - wrapInner(function(index)) - /// - /// - /// An HTML snippet, selector expression, jQuery object, or DOM element specifying the structure to wrap around the content of the matched elements. - /// - /// - - if (jQuery.isFunction(html)) { - return this.each(function (i) { - jQuery(this).wrapInner(html.call(this, i)); - }); - } - - return this.each(function () { - var self = jQuery(this), - contents = self.contents(); - - if (contents.length) { - contents.wrapAll(html); - - } else { - self.append(html); - } - }); - }; - jQuery.fn = jQuery.prototype; - jQuery.fn.init.prototype = jQuery.fn; - window.jQuery = window.$ = jQuery; -})(window); \ No newline at end of file diff --git a/DNN Platform/Website/Resources/Shared/scripts/jquery/jquery.js b/DNN Platform/Website/Resources/Shared/scripts/jquery/jquery.js index 50937333b99..1a86433c223 100644 --- a/DNN Platform/Website/Resources/Shared/scripts/jquery/jquery.js +++ b/DNN Platform/Website/Resources/Shared/scripts/jquery/jquery.js @@ -1,15 +1,12 @@ /*! - * jQuery JavaScript Library v3.5.1 + * jQuery JavaScript Library v3.7.1 * https://jquery.com/ * - * Includes Sizzle.js - * https://sizzlejs.com/ - * - * Copyright JS Foundation and other contributors + * Copyright OpenJS Foundation and other contributors * Released under the MIT license * https://jquery.org/license * - * Date: 2020-05-04T22:49Z + * Date: 2023-08-28T13:37Z */ ( function( global, factory ) { @@ -23,7 +20,7 @@ // (such as Node.js), expose a factory as module.exports. // This accentuates the need for the creation of a real `window`. // e.g. var jQuery = require("jquery")(window); - // See ticket #14549 for more info. + // See ticket trac-14549 for more info. module.exports = global.document ? factory( global, true ) : function( w ) { @@ -76,12 +73,16 @@ var support = {}; var isFunction = function isFunction( obj ) { - // Support: Chrome <=57, Firefox <=52 - // In some browsers, typeof returns "function" for HTML elements - // (i.e., `typeof document.createElement( "object" ) === "function"`). - // We don't want to classify *any* DOM node as a function. - return typeof obj === "function" && typeof obj.nodeType !== "number"; - }; + // Support: Chrome <=57, Firefox <=52 + // In some browsers, typeof returns "function" for HTML elements + // (i.e., `typeof document.createElement( "object" ) === "function"`). + // We don't want to classify *any* DOM node as a function. + // Support: QtWeb <=3.8.5, WebKit <=534.34, wkhtmltopdf tool <=0.12.5 + // Plus for old WebKit, typeof returns "function" for HTML collections + // (e.g., `typeof document.getElementsByTagName("div") === "function"`). (gh-4756) + return typeof obj === "function" && typeof obj.nodeType !== "number" && + typeof obj.item !== "function"; + }; var isWindow = function isWindow( obj ) { @@ -146,8 +147,9 @@ function toType( obj ) { -var - version = "3.5.1", +var version = "3.7.1", + + rhtmlSuffix = /HTML$/i, // Define a local copy of jQuery jQuery = function( selector, context ) { @@ -393,6 +395,38 @@ jQuery.extend( { return obj; }, + + // Retrieve the text value of an array of DOM nodes + text: function( elem ) { + var node, + ret = "", + i = 0, + nodeType = elem.nodeType; + + if ( !nodeType ) { + + // If no nodeType, this is expected to be an array + while ( ( node = elem[ i++ ] ) ) { + + // Do not traverse comment nodes + ret += jQuery.text( node ); + } + } + if ( nodeType === 1 || nodeType === 11 ) { + return elem.textContent; + } + if ( nodeType === 9 ) { + return elem.documentElement.textContent; + } + if ( nodeType === 3 || nodeType === 4 ) { + return elem.nodeValue; + } + + // Do not include comment or processing instruction nodes + + return ret; + }, + // results is for internal usage only makeArray: function( arr, results ) { var ret = results || []; @@ -401,7 +435,7 @@ jQuery.extend( { if ( isArrayLike( Object( arr ) ) ) { jQuery.merge( ret, typeof arr === "string" ? - [ arr ] : arr + [ arr ] : arr ); } else { push.call( ret, arr ); @@ -415,6 +449,15 @@ jQuery.extend( { return arr == null ? -1 : indexOf.call( arr, elem, i ); }, + isXMLDoc: function( elem ) { + var namespace = elem && elem.namespaceURI, + docElem = elem && ( elem.ownerDocument || elem ).documentElement; + + // Assume HTML when documentElement doesn't yet exist, such as inside + // document fragments. + return !rhtmlSuffix.test( namespace || docElem && docElem.nodeName || "HTML" ); + }, + // Support: Android <=4.0 only, PhantomJS 1 only // push.apply(_, arraylike) throws on ancient WebKit merge: function( first, second ) { @@ -496,9 +539,9 @@ if ( typeof Symbol === "function" ) { // Populate the class2type map jQuery.each( "Boolean Number String Function Array Date RegExp Object Error Symbol".split( " " ), -function( _i, name ) { - class2type[ "[object " + name + "]" ] = name.toLowerCase(); -} ); + function( _i, name ) { + class2type[ "[object " + name + "]" ] = name.toLowerCase(); + } ); function isArrayLike( obj ) { @@ -516,43 +559,98 @@ function isArrayLike( obj ) { return type === "array" || length === 0 || typeof length === "number" && length > 0 && ( length - 1 ) in obj; } -var Sizzle = -/*! - * Sizzle CSS Selector Engine v2.3.5 - * https://sizzlejs.com/ - * - * Copyright JS Foundation and other contributors - * Released under the MIT license - * https://js.foundation/ - * - * Date: 2020-03-14 - */ -( function( window ) { + + +function nodeName( elem, name ) { + + return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase(); + +} +var pop = arr.pop; + + +var sort = arr.sort; + + +var splice = arr.splice; + + +var whitespace = "[\\x20\\t\\r\\n\\f]"; + + +var rtrimCSS = new RegExp( + "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", + "g" +); + + + + +// Note: an element does not contain itself +jQuery.contains = function( a, b ) { + var bup = b && b.parentNode; + + return a === bup || !!( bup && bup.nodeType === 1 && ( + + // Support: IE 9 - 11+ + // IE doesn't have `contains` on SVG. + a.contains ? + a.contains( bup ) : + a.compareDocumentPosition && a.compareDocumentPosition( bup ) & 16 + ) ); +}; + + + + +// CSS string/identifier serialization +// https://drafts.csswg.org/cssom/#common-serializing-idioms +var rcssescape = /([\0-\x1f\x7f]|^-?\d)|^-$|[^\x80-\uFFFF\w-]/g; + +function fcssescape( ch, asCodePoint ) { + if ( asCodePoint ) { + + // U+0000 NULL becomes U+FFFD REPLACEMENT CHARACTER + if ( ch === "\0" ) { + return "\uFFFD"; + } + + // Control characters and (dependent upon position) numbers get escaped as code points + return ch.slice( 0, -1 ) + "\\" + ch.charCodeAt( ch.length - 1 ).toString( 16 ) + " "; + } + + // Other potentially-special ASCII characters get backslash-escaped + return "\\" + ch; +} + +jQuery.escapeSelector = function( sel ) { + return ( sel + "" ).replace( rcssescape, fcssescape ); +}; + + + + +var preferredDoc = document, + pushNative = push; + +( function() { + var i, - support, Expr, - getText, - isXML, - tokenize, - compile, - select, outermostContext, sortInput, hasDuplicate, + push = pushNative, // Local document vars - setDocument, document, - docElem, + documentElement, documentIsHTML, rbuggyQSA, - rbuggyMatches, matches, - contains, // Instance-specific data - expando = "sizzle" + 1 * new Date(), - preferredDoc = window.document, + expando = jQuery.expando, dirruns = 0, done = 0, classCache = createCache(), @@ -566,47 +664,22 @@ var i, return 0; }, - // Instance methods - hasOwn = ( {} ).hasOwnProperty, - arr = [], - pop = arr.pop, - pushNative = arr.push, - push = arr.push, - slice = arr.slice, - - // Use a stripped-down indexOf as it's faster than native - // https://jsperf.com/thor-indexof-vs-for/5 - indexOf = function( list, elem ) { - var i = 0, - len = list.length; - for ( ; i < len; i++ ) { - if ( list[ i ] === elem ) { - return i; - } - } - return -1; - }, - - booleans = "checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|" + - "ismap|loop|multiple|open|readonly|required|scoped", + booleans = "checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|" + + "loop|multiple|open|readonly|required|scoped", // Regular expressions - // http://www.w3.org/TR/css3-selectors/#whitespace - whitespace = "[\\x20\\t\\r\\n\\f]", - // https://www.w3.org/TR/css-syntax-3/#ident-token-diagram identifier = "(?:\\\\[\\da-fA-F]{1,6}" + whitespace + "?|\\\\[^\\r\\n\\f]|[\\w-]|[^\0-\\x7f])+", - // Attribute selectors: http://www.w3.org/TR/selectors/#attribute-selectors + // Attribute selectors: https://www.w3.org/TR/selectors/#attribute-selectors attributes = "\\[" + whitespace + "*(" + identifier + ")(?:" + whitespace + // Operator (capture 2) "*([*^$|!~]?=)" + whitespace + - // "Attribute values must be CSS identifiers [capture 5] - // or strings [capture 3 or capture 4]" + // "Attribute values must be CSS identifiers [capture 5] or strings [capture 3 or capture 4]" "*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|(" + identifier + "))|)" + whitespace + "*\\]", @@ -625,101 +698,88 @@ var i, // Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter rwhitespace = new RegExp( whitespace + "+", "g" ), - rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + - whitespace + "+$", "g" ), rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ), - rcombinators = new RegExp( "^" + whitespace + "*([>+~]|" + whitespace + ")" + whitespace + - "*" ), + rleadingCombinator = new RegExp( "^" + whitespace + "*([>+~]|" + whitespace + ")" + + whitespace + "*" ), rdescend = new RegExp( whitespace + "|>" ), rpseudo = new RegExp( pseudos ), ridentifier = new RegExp( "^" + identifier + "$" ), matchExpr = { - "ID": new RegExp( "^#(" + identifier + ")" ), - "CLASS": new RegExp( "^\\.(" + identifier + ")" ), - "TAG": new RegExp( "^(" + identifier + "|[*])" ), - "ATTR": new RegExp( "^" + attributes ), - "PSEUDO": new RegExp( "^" + pseudos ), - "CHILD": new RegExp( "^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + - whitespace + "*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + - whitespace + "*(\\d+)|))" + whitespace + "*\\)|)", "i" ), - "bool": new RegExp( "^(?:" + booleans + ")$", "i" ), + ID: new RegExp( "^#(" + identifier + ")" ), + CLASS: new RegExp( "^\\.(" + identifier + ")" ), + TAG: new RegExp( "^(" + identifier + "|[*])" ), + ATTR: new RegExp( "^" + attributes ), + PSEUDO: new RegExp( "^" + pseudos ), + CHILD: new RegExp( + "^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + + whitespace + "*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + + whitespace + "*(\\d+)|))" + whitespace + "*\\)|)", "i" ), + bool: new RegExp( "^(?:" + booleans + ")$", "i" ), // For use in libraries implementing .is() // We use this for POS matching in `select` - "needsContext": new RegExp( "^" + whitespace + + needsContext: new RegExp( "^" + whitespace + "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" + whitespace + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", "i" ) }, - rhtml = /HTML$/i, rinputs = /^(?:input|select|textarea|button)$/i, rheader = /^h\d$/i, - rnative = /^[^{]+\{\s*\[native \w/, - // Easily-parseable/retrievable ID or TAG or CLASS selectors rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/, rsibling = /[+~]/, // CSS escapes - // http://www.w3.org/TR/CSS21/syndata.html#escaped-characters - runescape = new RegExp( "\\\\[\\da-fA-F]{1,6}" + whitespace + "?|\\\\([^\\r\\n\\f])", "g" ), + // https://www.w3.org/TR/CSS21/syndata.html#escaped-characters + runescape = new RegExp( "\\\\[\\da-fA-F]{1,6}" + whitespace + + "?|\\\\([^\\r\\n\\f])", "g" ), funescape = function( escape, nonHex ) { var high = "0x" + escape.slice( 1 ) - 0x10000; - return nonHex ? + if ( nonHex ) { // Strip the backslash prefix from a non-hex escape sequence - nonHex : - - // Replace a hexadecimal escape sequence with the encoded Unicode code point - // Support: IE <=11+ - // For values outside the Basic Multilingual Plane (BMP), manually construct a - // surrogate pair - high < 0 ? - String.fromCharCode( high + 0x10000 ) : - String.fromCharCode( high >> 10 | 0xD800, high & 0x3FF | 0xDC00 ); - }, - - // CSS string/identifier serialization - // https://drafts.csswg.org/cssom/#common-serializing-idioms - rcssescape = /([\0-\x1f\x7f]|^-?\d)|^-$|[^\0-\x1f\x7f-\uFFFF\w-]/g, - fcssescape = function( ch, asCodePoint ) { - if ( asCodePoint ) { - - // U+0000 NULL becomes U+FFFD REPLACEMENT CHARACTER - if ( ch === "\0" ) { - return "\uFFFD"; - } - - // Control characters and (dependent upon position) numbers get escaped as code points - return ch.slice( 0, -1 ) + "\\" + - ch.charCodeAt( ch.length - 1 ).toString( 16 ) + " "; + return nonHex; } - // Other potentially-special ASCII characters get backslash-escaped - return "\\" + ch; + // Replace a hexadecimal escape sequence with the encoded Unicode code point + // Support: IE <=11+ + // For values outside the Basic Multilingual Plane (BMP), manually construct a + // surrogate pair + return high < 0 ? + String.fromCharCode( high + 0x10000 ) : + String.fromCharCode( high >> 10 | 0xD800, high & 0x3FF | 0xDC00 ); }, - // Used for iframes - // See setDocument() + // Used for iframes; see `setDocument`. + // Support: IE 9 - 11+, Edge 12 - 18+ // Removing the function wrapper causes a "Permission Denied" - // error in IE + // error in IE/Edge. unloadHandler = function() { setDocument(); }, inDisabledFieldset = addCombinator( function( elem ) { - return elem.disabled === true && elem.nodeName.toLowerCase() === "fieldset"; + return elem.disabled === true && nodeName( elem, "fieldset" ); }, { dir: "parentNode", next: "legend" } ); +// Support: IE <=9 only +// Accessing document.activeElement can throw unexpectedly +// https://bugs.jquery.com/ticket/13393 +function safeActiveElement() { + try { + return document.activeElement; + } catch ( err ) { } +} + // Optimize for push.apply( _, NodeList ) try { push.apply( @@ -727,32 +787,22 @@ try { preferredDoc.childNodes ); - // Support: Android<4.0 + // Support: Android <=4.0 // Detect silently failing push.apply // eslint-disable-next-line no-unused-expressions arr[ preferredDoc.childNodes.length ].nodeType; } catch ( e ) { - push = { apply: arr.length ? - - // Leverage slice if possible - function( target, els ) { + push = { + apply: function( target, els ) { pushNative.apply( target, slice.call( els ) ); - } : - - // Support: IE<9 - // Otherwise append directly - function( target, els ) { - var j = target.length, - i = 0; - - // Can't trust NodeList.length - while ( ( target[ j++ ] = els[ i++ ] ) ) {} - target.length = j - 1; + }, + call: function( target ) { + pushNative.apply( target, slice.call( arguments, 1 ) ); } }; } -function Sizzle( selector, context, results, seed ) { +function find( selector, context, results, seed ) { var m, i, elem, nid, match, groups, newSelector, newContext = context && context.ownerDocument, @@ -786,11 +836,10 @@ function Sizzle( selector, context, results, seed ) { if ( nodeType === 9 ) { if ( ( elem = context.getElementById( m ) ) ) { - // Support: IE, Opera, Webkit - // TODO: identify versions + // Support: IE 9 only // getElementById can match elements by name instead of ID if ( elem.id === m ) { - results.push( elem ); + push.call( results, elem ); return results; } } else { @@ -800,14 +849,13 @@ function Sizzle( selector, context, results, seed ) { // Element context } else { - // Support: IE, Opera, Webkit - // TODO: identify versions + // Support: IE 9 only // getElementById can match elements by name instead of ID if ( newContext && ( elem = newContext.getElementById( m ) ) && - contains( context, elem ) && + find.contains( context, elem ) && elem.id === m ) { - results.push( elem ); + push.call( results, elem ); return results; } } @@ -818,22 +866,15 @@ function Sizzle( selector, context, results, seed ) { return results; // Class selector - } else if ( ( m = match[ 3 ] ) && support.getElementsByClassName && - context.getElementsByClassName ) { - + } else if ( ( m = match[ 3 ] ) && context.getElementsByClassName ) { push.apply( results, context.getElementsByClassName( m ) ); return results; } } // Take advantage of querySelectorAll - if ( support.qsa && - !nonnativeSelectorCache[ selector + " " ] && - ( !rbuggyQSA || !rbuggyQSA.test( selector ) ) && - - // Support: IE 8 only - // Exclude object elements - ( nodeType !== 1 || context.nodeName.toLowerCase() !== "object" ) ) { + if ( !nonnativeSelectorCache[ selector + " " ] && + ( !rbuggyQSA || !rbuggyQSA.test( selector ) ) ) { newSelector = selector; newContext = context; @@ -846,7 +887,7 @@ function Sizzle( selector, context, results, seed ) { // as such selectors are not recognized by querySelectorAll. // Thanks to Andrew Dupont for this technique. if ( nodeType === 1 && - ( rdescend.test( selector ) || rcombinators.test( selector ) ) ) { + ( rdescend.test( selector ) || rleadingCombinator.test( selector ) ) ) { // Expand context for sibling selectors newContext = rsibling.test( selector ) && testContext( context.parentNode ) || @@ -854,11 +895,15 @@ function Sizzle( selector, context, results, seed ) { // We can use :scope instead of the ID hack if the browser // supports it & if we're not changing the context. - if ( newContext !== context || !support.scope ) { + // Support: IE 11+, Edge 17 - 18+ + // IE/Edge sometimes throw a "Permission denied" error when + // strict-comparing two documents; shallow comparisons work. + // eslint-disable-next-line eqeqeq + if ( newContext != context || !support.scope ) { // Capture the context ID, setting it first if necessary if ( ( nid = context.getAttribute( "id" ) ) ) { - nid = nid.replace( rcssescape, fcssescape ); + nid = jQuery.escapeSelector( nid ); } else { context.setAttribute( "id", ( nid = expando ) ); } @@ -891,7 +936,7 @@ function Sizzle( selector, context, results, seed ) { } // All others - return select( selector.replace( rtrim, "$1" ), context, results, seed ); + return select( selector.replace( rtrimCSS, "$1" ), context, results, seed ); } /** @@ -905,7 +950,8 @@ function createCache() { function cache( key, value ) { - // Use (key + " ") to avoid collision with native prototype properties (see Issue #157) + // Use (key + " ") to avoid collision with native prototype properties + // (see https://github.com/jquery/sizzle/issues/157) if ( keys.push( key + " " ) > Expr.cacheLength ) { // Only keep the most recent entries @@ -917,7 +963,7 @@ function createCache() { } /** - * Mark a function for special use by Sizzle + * Mark a function for special use by jQuery selector module * @param {Function} fn The function to mark */ function markFunction( fn ) { @@ -948,56 +994,13 @@ function assert( fn ) { } } -/** - * Adds the same handler for all of the specified attrs - * @param {String} attrs Pipe-separated list of attributes - * @param {Function} handler The method that will be applied - */ -function addHandle( attrs, handler ) { - var arr = attrs.split( "|" ), - i = arr.length; - - while ( i-- ) { - Expr.attrHandle[ arr[ i ] ] = handler; - } -} - -/** - * Checks document order of two siblings - * @param {Element} a - * @param {Element} b - * @returns {Number} Returns less than 0 if a precedes b, greater than 0 if a follows b - */ -function siblingCheck( a, b ) { - var cur = b && a, - diff = cur && a.nodeType === 1 && b.nodeType === 1 && - a.sourceIndex - b.sourceIndex; - - // Use IE sourceIndex if available on both nodes - if ( diff ) { - return diff; - } - - // Check if b follows a - if ( cur ) { - while ( ( cur = cur.nextSibling ) ) { - if ( cur === b ) { - return -1; - } - } - } - - return a ? 1 : -1; -} - /** * Returns a function to use in pseudos for input types * @param {String} type */ function createInputPseudo( type ) { return function( elem ) { - var name = elem.nodeName.toLowerCase(); - return name === "input" && elem.type === type; + return nodeName( elem, "input" ) && elem.type === type; }; } @@ -1007,8 +1010,8 @@ function createInputPseudo( type ) { */ function createButtonPseudo( type ) { return function( elem ) { - var name = elem.nodeName.toLowerCase(); - return ( name === "input" || name === "button" ) && elem.type === type; + return ( nodeName( elem, "input" ) || nodeName( elem, "button" ) ) && + elem.type === type; }; } @@ -1044,14 +1047,13 @@ function createDisabledPseudo( disabled ) { } } - // Support: IE 6 - 11 + // Support: IE 6 - 11+ // Use the isDisabled shortcut property to check for disabled fieldset ancestors return elem.isDisabled === disabled || // Where there is no isDisabled, check manually - /* jshint -W018 */ elem.isDisabled !== !disabled && - inDisabledFieldset( elem ) === disabled; + inDisabledFieldset( elem ) === disabled; } return elem.disabled === disabled; @@ -1091,7 +1093,7 @@ function createPositionalPseudo( fn ) { } /** - * Checks a node for validity as a Sizzle context + * Checks a node for validity as a jQuery selector context * @param {Element|Object=} context * @returns {Element|Object|Boolean} The input node if acceptable, otherwise a falsy value */ @@ -1099,31 +1101,13 @@ function testContext( context ) { return context && typeof context.getElementsByTagName !== "undefined" && context; } -// Expose support vars for convenience -support = Sizzle.support = {}; - -/** - * Detects XML nodes - * @param {Element|Object} elem An element or a document - * @returns {Boolean} True iff elem is a non-HTML XML node - */ -isXML = Sizzle.isXML = function( elem ) { - var namespace = elem.namespaceURI, - docElem = ( elem.ownerDocument || elem ).documentElement; - - // Support: IE <=8 - // Assume HTML when documentElement doesn't yet exist, such as inside loading iframes - // https://bugs.jquery.com/ticket/4833 - return !rhtml.test( namespace || docElem && docElem.nodeName || "HTML" ); -}; - /** * Sets document-related variables once based on the current document - * @param {Element|Object} [doc] An element or document object to use to set the document + * @param {Element|Object} [node] An element or document object to use to set the document * @returns {Object} Returns the current document */ -setDocument = Sizzle.setDocument = function( node ) { - var hasCompare, subWindow, +function setDocument( node ) { + var subWindow, doc = node ? node.ownerDocument || node : preferredDoc; // Return early if doc is invalid or already selected @@ -1137,87 +1121,90 @@ setDocument = Sizzle.setDocument = function( node ) { // Update global variables document = doc; - docElem = document.documentElement; - documentIsHTML = !isXML( document ); + documentElement = document.documentElement; + documentIsHTML = !jQuery.isXMLDoc( document ); + + // Support: iOS 7 only, IE 9 - 11+ + // Older browsers didn't support unprefixed `matches`. + matches = documentElement.matches || + documentElement.webkitMatchesSelector || + documentElement.msMatchesSelector; // Support: IE 9 - 11+, Edge 12 - 18+ - // Accessing iframe documents after unload throws "permission denied" errors (jQuery #13936) - // Support: IE 11+, Edge 17 - 18+ - // IE/Edge sometimes throw a "Permission denied" error when strict-comparing - // two documents; shallow comparisons work. - // eslint-disable-next-line eqeqeq - if ( preferredDoc != document && - ( subWindow = document.defaultView ) && subWindow.top !== subWindow ) { + // Accessing iframe documents after unload throws "permission denied" errors + // (see trac-13936). + // Limit the fix to IE & Edge Legacy; despite Edge 15+ implementing `matches`, + // all IE 9+ and Edge Legacy versions implement `msMatchesSelector` as well. + if ( documentElement.msMatchesSelector && - // Support: IE 11, Edge - if ( subWindow.addEventListener ) { - subWindow.addEventListener( "unload", unloadHandler, false ); + // Support: IE 11+, Edge 17 - 18+ + // IE/Edge sometimes throw a "Permission denied" error when strict-comparing + // two documents; shallow comparisons work. + // eslint-disable-next-line eqeqeq + preferredDoc != document && + ( subWindow = document.defaultView ) && subWindow.top !== subWindow ) { - // Support: IE 9 - 10 only - } else if ( subWindow.attachEvent ) { - subWindow.attachEvent( "onunload", unloadHandler ); - } + // Support: IE 9 - 11+, Edge 12 - 18+ + subWindow.addEventListener( "unload", unloadHandler ); } - // Support: IE 8 - 11+, Edge 12 - 18+, Chrome <=16 - 25 only, Firefox <=3.6 - 31 only, - // Safari 4 - 5 only, Opera <=11.6 - 12.x only - // IE/Edge & older browsers don't support the :scope pseudo-class. - // Support: Safari 6.0 only - // Safari 6.0 supports :scope but it's an alias of :root there. - support.scope = assert( function( el ) { - docElem.appendChild( el ).appendChild( document.createElement( "div" ) ); - return typeof el.querySelectorAll !== "undefined" && - !el.querySelectorAll( ":scope fieldset div" ).length; + // Support: IE <10 + // Check if getElementById returns elements by name + // The broken getElementById methods don't pick up programmatically-set names, + // so use a roundabout getElementsByName test + support.getById = assert( function( el ) { + documentElement.appendChild( el ).id = jQuery.expando; + return !document.getElementsByName || + !document.getElementsByName( jQuery.expando ).length; } ); - /* Attributes - ---------------------------------------------------------------------- */ - - // Support: IE<8 - // Verify that getAttribute really returns attributes and not properties - // (excepting IE8 booleans) - support.attributes = assert( function( el ) { - el.className = "i"; - return !el.getAttribute( "className" ); + // Support: IE 9 only + // Check to see if it's possible to do matchesSelector + // on a disconnected node. + support.disconnectedMatch = assert( function( el ) { + return matches.call( el, "*" ); } ); - /* getElement(s)By* - ---------------------------------------------------------------------- */ - - // Check if getElementsByTagName("*") returns only elements - support.getElementsByTagName = assert( function( el ) { - el.appendChild( document.createComment( "" ) ); - return !el.getElementsByTagName( "*" ).length; + // Support: IE 9 - 11+, Edge 12 - 18+ + // IE/Edge don't support the :scope pseudo-class. + support.scope = assert( function() { + return document.querySelectorAll( ":scope" ); } ); - // Support: IE<9 - support.getElementsByClassName = rnative.test( document.getElementsByClassName ); - - // Support: IE<10 - // Check if getElementById returns elements by name - // The broken getElementById methods don't pick up programmatically-set names, - // so use a roundabout getElementsByName test - support.getById = assert( function( el ) { - docElem.appendChild( el ).id = expando; - return !document.getElementsByName || !document.getElementsByName( expando ).length; + // Support: Chrome 105 - 111 only, Safari 15.4 - 16.3 only + // Make sure the `:has()` argument is parsed unforgivingly. + // We include `*` in the test to detect buggy implementations that are + // _selectively_ forgiving (specifically when the list includes at least + // one valid selector). + // Note that we treat complete lack of support for `:has()` as if it were + // spec-compliant support, which is fine because use of `:has()` in such + // environments will fail in the qSA path and fall back to jQuery traversal + // anyway. + support.cssHas = assert( function() { + try { + document.querySelector( ":has(*,:jqfake)" ); + return false; + } catch ( e ) { + return true; + } } ); // ID filter and find if ( support.getById ) { - Expr.filter[ "ID" ] = function( id ) { + Expr.filter.ID = function( id ) { var attrId = id.replace( runescape, funescape ); return function( elem ) { return elem.getAttribute( "id" ) === attrId; }; }; - Expr.find[ "ID" ] = function( id, context ) { + Expr.find.ID = function( id, context ) { if ( typeof context.getElementById !== "undefined" && documentIsHTML ) { var elem = context.getElementById( id ); return elem ? [ elem ] : []; } }; } else { - Expr.filter[ "ID" ] = function( id ) { + Expr.filter.ID = function( id ) { var attrId = id.replace( runescape, funescape ); return function( elem ) { var node = typeof elem.getAttributeNode !== "undefined" && @@ -1228,7 +1215,7 @@ setDocument = Sizzle.setDocument = function( node ) { // Support: IE 6 - 7 only // getElementById is not reliable as a find shortcut - Expr.find[ "ID" ] = function( id, context ) { + Expr.find.ID = function( id, context ) { if ( typeof context.getElementById !== "undefined" && documentIsHTML ) { var node, i, elems, elem = context.getElementById( id ); @@ -1258,40 +1245,18 @@ setDocument = Sizzle.setDocument = function( node ) { } // Tag - Expr.find[ "TAG" ] = support.getElementsByTagName ? - function( tag, context ) { - if ( typeof context.getElementsByTagName !== "undefined" ) { - return context.getElementsByTagName( tag ); - - // DocumentFragment nodes don't have gEBTN - } else if ( support.qsa ) { - return context.querySelectorAll( tag ); - } - } : - - function( tag, context ) { - var elem, - tmp = [], - i = 0, + Expr.find.TAG = function( tag, context ) { + if ( typeof context.getElementsByTagName !== "undefined" ) { + return context.getElementsByTagName( tag ); - // By happy coincidence, a (broken) gEBTN appears on DocumentFragment nodes too - results = context.getElementsByTagName( tag ); - - // Filter out possible comments - if ( tag === "*" ) { - while ( ( elem = results[ i++ ] ) ) { - if ( elem.nodeType === 1 ) { - tmp.push( elem ); - } - } - - return tmp; - } - return results; - }; + // DocumentFragment nodes don't have gEBTN + } else { + return context.querySelectorAll( tag ); + } + }; // Class - Expr.find[ "CLASS" ] = support.getElementsByClassName && function( className, context ) { + Expr.find.CLASS = function( className, context ) { if ( typeof context.getElementsByClassName !== "undefined" && documentIsHTML ) { return context.getElementsByClassName( className ); } @@ -1302,177 +1267,94 @@ setDocument = Sizzle.setDocument = function( node ) { // QSA and matchesSelector support - // matchesSelector(:active) reports false when true (IE9/Opera 11.5) - rbuggyMatches = []; - - // qSa(:focus) reports false when true (Chrome 21) - // We allow this because of a bug in IE8/9 that throws an error - // whenever `document.activeElement` is accessed on an iframe - // So, we allow :focus to pass through QSA all the time to avoid the IE error - // See https://bugs.jquery.com/ticket/13378 rbuggyQSA = []; - if ( ( support.qsa = rnative.test( document.querySelectorAll ) ) ) { - - // Build QSA regex - // Regex strategy adopted from Diego Perini - assert( function( el ) { - - var input; - - // Select is set to empty string on purpose - // This is to test IE's treatment of not explicitly - // setting a boolean content attribute, - // since its presence should be enough - // https://bugs.jquery.com/ticket/12359 - docElem.appendChild( el ).innerHTML = "" + - ""; - - // Support: IE8, Opera 11-12.16 - // Nothing should be selected when empty strings follow ^= or $= or *= - // The test attribute must be unknown in Opera but "safe" for WinRT - // https://msdn.microsoft.com/en-us/library/ie/hh465388.aspx#attribute_section - if ( el.querySelectorAll( "[msallowcapture^='']" ).length ) { - rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:''|\"\")" ); - } - - // Support: IE8 - // Boolean attributes and "value" are not treated correctly - if ( !el.querySelectorAll( "[selected]" ).length ) { - rbuggyQSA.push( "\\[" + whitespace + "*(?:value|" + booleans + ")" ); - } - - // Support: Chrome<29, Android<4.4, Safari<7.0+, iOS<7.0+, PhantomJS<1.9.8+ - if ( !el.querySelectorAll( "[id~=" + expando + "-]" ).length ) { - rbuggyQSA.push( "~=" ); - } - - // Support: IE 11+, Edge 15 - 18+ - // IE 11/Edge don't find elements on a `[name='']` query in some cases. - // Adding a temporary attribute to the document before the selection works - // around the issue. - // Interestingly, IE 10 & older don't seem to have the issue. - input = document.createElement( "input" ); - input.setAttribute( "name", "" ); - el.appendChild( input ); - if ( !el.querySelectorAll( "[name='']" ).length ) { - rbuggyQSA.push( "\\[" + whitespace + "*name" + whitespace + "*=" + - whitespace + "*(?:''|\"\")" ); - } - - // Webkit/Opera - :checked should return selected option elements - // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked - // IE8 throws error here and will not see later tests - if ( !el.querySelectorAll( ":checked" ).length ) { - rbuggyQSA.push( ":checked" ); - } - - // Support: Safari 8+, iOS 8+ - // https://bugs.webkit.org/show_bug.cgi?id=136851 - // In-page `selector#id sibling-combinator selector` fails - if ( !el.querySelectorAll( "a#" + expando + "+*" ).length ) { - rbuggyQSA.push( ".#.+[+~]" ); - } - - // Support: Firefox <=3.6 - 5 only - // Old Firefox doesn't throw on a badly-escaped identifier. - el.querySelectorAll( "\\\f" ); - rbuggyQSA.push( "[\\r\\n\\f]" ); - } ); + // Build QSA regex + // Regex strategy adopted from Diego Perini + assert( function( el ) { - assert( function( el ) { - el.innerHTML = "" + - ""; + var input; - // Support: Windows 8 Native Apps - // The type and name attributes are restricted during .innerHTML assignment - var input = document.createElement( "input" ); - input.setAttribute( "type", "hidden" ); - el.appendChild( input ).setAttribute( "name", "D" ); + documentElement.appendChild( el ).innerHTML = + "" + + ""; - // Support: IE8 - // Enforce case-sensitivity of name attribute - if ( el.querySelectorAll( "[name=d]" ).length ) { - rbuggyQSA.push( "name" + whitespace + "*[*^$|!~]?=" ); - } - - // FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled) - // IE8 throws error here and will not see later tests - if ( el.querySelectorAll( ":enabled" ).length !== 2 ) { - rbuggyQSA.push( ":enabled", ":disabled" ); - } + // Support: iOS <=7 - 8 only + // Boolean attributes and "value" are not treated correctly in some XML documents + if ( !el.querySelectorAll( "[selected]" ).length ) { + rbuggyQSA.push( "\\[" + whitespace + "*(?:value|" + booleans + ")" ); + } - // Support: IE9-11+ - // IE's :disabled selector does not pick up the children of disabled fieldsets - docElem.appendChild( el ).disabled = true; - if ( el.querySelectorAll( ":disabled" ).length !== 2 ) { - rbuggyQSA.push( ":enabled", ":disabled" ); - } + // Support: iOS <=7 - 8 only + if ( !el.querySelectorAll( "[id~=" + expando + "-]" ).length ) { + rbuggyQSA.push( "~=" ); + } - // Support: Opera 10 - 11 only - // Opera 10-11 does not throw on post-comma invalid pseudos - el.querySelectorAll( "*,:x" ); - rbuggyQSA.push( ",.*:" ); - } ); - } + // Support: iOS 8 only + // https://bugs.webkit.org/show_bug.cgi?id=136851 + // In-page `selector#id sibling-combinator selector` fails + if ( !el.querySelectorAll( "a#" + expando + "+*" ).length ) { + rbuggyQSA.push( ".#.+[+~]" ); + } - if ( ( support.matchesSelector = rnative.test( ( matches = docElem.matches || - docElem.webkitMatchesSelector || - docElem.mozMatchesSelector || - docElem.oMatchesSelector || - docElem.msMatchesSelector ) ) ) ) { + // Support: Chrome <=105+, Firefox <=104+, Safari <=15.4+ + // In some of the document kinds, these selectors wouldn't work natively. + // This is probably OK but for backwards compatibility we want to maintain + // handling them through jQuery traversal in jQuery 3.x. + if ( !el.querySelectorAll( ":checked" ).length ) { + rbuggyQSA.push( ":checked" ); + } - assert( function( el ) { + // Support: Windows 8 Native Apps + // The type and name attributes are restricted during .innerHTML assignment + input = document.createElement( "input" ); + input.setAttribute( "type", "hidden" ); + el.appendChild( input ).setAttribute( "name", "D" ); + + // Support: IE 9 - 11+ + // IE's :disabled selector does not pick up the children of disabled fieldsets + // Support: Chrome <=105+, Firefox <=104+, Safari <=15.4+ + // In some of the document kinds, these selectors wouldn't work natively. + // This is probably OK but for backwards compatibility we want to maintain + // handling them through jQuery traversal in jQuery 3.x. + documentElement.appendChild( el ).disabled = true; + if ( el.querySelectorAll( ":disabled" ).length !== 2 ) { + rbuggyQSA.push( ":enabled", ":disabled" ); + } + + // Support: IE 11+, Edge 15 - 18+ + // IE 11/Edge don't find elements on a `[name='']` query in some cases. + // Adding a temporary attribute to the document before the selection works + // around the issue. + // Interestingly, IE 10 & older don't seem to have the issue. + input = document.createElement( "input" ); + input.setAttribute( "name", "" ); + el.appendChild( input ); + if ( !el.querySelectorAll( "[name='']" ).length ) { + rbuggyQSA.push( "\\[" + whitespace + "*name" + whitespace + "*=" + + whitespace + "*(?:''|\"\")" ); + } + } ); - // Check to see if it's possible to do matchesSelector - // on a disconnected node (IE 9) - support.disconnectedMatch = matches.call( el, "*" ); + if ( !support.cssHas ) { - // This should fail with an exception - // Gecko does not error, returns false instead - matches.call( el, "[s!='']:x" ); - rbuggyMatches.push( "!=", pseudos ); - } ); + // Support: Chrome 105 - 110+, Safari 15.4 - 16.3+ + // Our regular `try-catch` mechanism fails to detect natively-unsupported + // pseudo-classes inside `:has()` (such as `:has(:contains("Foo"))`) + // in browsers that parse the `:has()` argument as a forgiving selector list. + // https://drafts.csswg.org/selectors/#relational now requires the argument + // to be parsed unforgivingly, but browsers have not yet fully adjusted. + rbuggyQSA.push( ":has" ); } rbuggyQSA = rbuggyQSA.length && new RegExp( rbuggyQSA.join( "|" ) ); - rbuggyMatches = rbuggyMatches.length && new RegExp( rbuggyMatches.join( "|" ) ); - - /* Contains - ---------------------------------------------------------------------- */ - hasCompare = rnative.test( docElem.compareDocumentPosition ); - - // Element contains another - // Purposefully self-exclusive - // As in, an element does not contain itself - contains = hasCompare || rnative.test( docElem.contains ) ? - function( a, b ) { - var adown = a.nodeType === 9 ? a.documentElement : a, - bup = b && b.parentNode; - return a === bup || !!( bup && bup.nodeType === 1 && ( - adown.contains ? - adown.contains( bup ) : - a.compareDocumentPosition && a.compareDocumentPosition( bup ) & 16 - ) ); - } : - function( a, b ) { - if ( b ) { - while ( ( b = b.parentNode ) ) { - if ( b === a ) { - return true; - } - } - } - return false; - }; /* Sorting ---------------------------------------------------------------------- */ // Document order sorting - sortOrder = hasCompare ? - function( a, b ) { + sortOrder = function( a, b ) { // Flag for duplicate removal if ( a === b ) { @@ -1506,8 +1388,8 @@ setDocument = Sizzle.setDocument = function( node ) { // IE/Edge sometimes throw a "Permission denied" error when strict-comparing // two documents; shallow comparisons work. // eslint-disable-next-line eqeqeq - if ( a == document || a.ownerDocument == preferredDoc && - contains( preferredDoc, a ) ) { + if ( a === document || a.ownerDocument == preferredDoc && + find.contains( preferredDoc, a ) ) { return -1; } @@ -1515,100 +1397,33 @@ setDocument = Sizzle.setDocument = function( node ) { // IE/Edge sometimes throw a "Permission denied" error when strict-comparing // two documents; shallow comparisons work. // eslint-disable-next-line eqeqeq - if ( b == document || b.ownerDocument == preferredDoc && - contains( preferredDoc, b ) ) { + if ( b === document || b.ownerDocument == preferredDoc && + find.contains( preferredDoc, b ) ) { return 1; } // Maintain original order return sortInput ? - ( indexOf( sortInput, a ) - indexOf( sortInput, b ) ) : + ( indexOf.call( sortInput, a ) - indexOf.call( sortInput, b ) ) : 0; } return compare & 4 ? -1 : 1; - } : - function( a, b ) { - - // Exit early if the nodes are identical - if ( a === b ) { - hasDuplicate = true; - return 0; - } - - var cur, - i = 0, - aup = a.parentNode, - bup = b.parentNode, - ap = [ a ], - bp = [ b ]; - - // Parentless nodes are either documents or disconnected - if ( !aup || !bup ) { - - // Support: IE 11+, Edge 17 - 18+ - // IE/Edge sometimes throw a "Permission denied" error when strict-comparing - // two documents; shallow comparisons work. - /* eslint-disable eqeqeq */ - return a == document ? -1 : - b == document ? 1 : - /* eslint-enable eqeqeq */ - aup ? -1 : - bup ? 1 : - sortInput ? - ( indexOf( sortInput, a ) - indexOf( sortInput, b ) ) : - 0; - - // If the nodes are siblings, we can do a quick check - } else if ( aup === bup ) { - return siblingCheck( a, b ); - } - - // Otherwise we need full lists of their ancestors for comparison - cur = a; - while ( ( cur = cur.parentNode ) ) { - ap.unshift( cur ); - } - cur = b; - while ( ( cur = cur.parentNode ) ) { - bp.unshift( cur ); - } - - // Walk down the tree looking for a discrepancy - while ( ap[ i ] === bp[ i ] ) { - i++; - } - - return i ? - - // Do a sibling check if the nodes have a common ancestor - siblingCheck( ap[ i ], bp[ i ] ) : - - // Otherwise nodes in our document sort first - // Support: IE 11+, Edge 17 - 18+ - // IE/Edge sometimes throw a "Permission denied" error when strict-comparing - // two documents; shallow comparisons work. - /* eslint-disable eqeqeq */ - ap[ i ] == preferredDoc ? -1 : - bp[ i ] == preferredDoc ? 1 : - /* eslint-enable eqeqeq */ - 0; }; return document; -}; +} -Sizzle.matches = function( expr, elements ) { - return Sizzle( expr, null, null, elements ); +find.matches = function( expr, elements ) { + return find( expr, null, null, elements ); }; -Sizzle.matchesSelector = function( elem, expr ) { +find.matchesSelector = function( elem, expr ) { setDocument( elem ); - if ( support.matchesSelector && documentIsHTML && + if ( documentIsHTML && !nonnativeSelectorCache[ expr + " " ] && - ( !rbuggyMatches || !rbuggyMatches.test( expr ) ) && - ( !rbuggyQSA || !rbuggyQSA.test( expr ) ) ) { + ( !rbuggyQSA || !rbuggyQSA.test( expr ) ) ) { try { var ret = matches.call( elem, expr ); @@ -1616,9 +1431,9 @@ Sizzle.matchesSelector = function( elem, expr ) { // IE 9's matchesSelector returns false on disconnected nodes if ( ret || support.disconnectedMatch || - // As well, disconnected nodes are said to be in a document - // fragment in IE 9 - elem.document && elem.document.nodeType !== 11 ) { + // As well, disconnected nodes are said to be in a document + // fragment in IE 9 + elem.document && elem.document.nodeType !== 11 ) { return ret; } } catch ( e ) { @@ -1626,10 +1441,10 @@ Sizzle.matchesSelector = function( elem, expr ) { } } - return Sizzle( expr, document, null, [ elem ] ).length > 0; + return find( expr, document, null, [ elem ] ).length > 0; }; -Sizzle.contains = function( context, elem ) { +find.contains = function( context, elem ) { // Set document vars if needed // Support: IE 11+, Edge 17 - 18+ @@ -1639,10 +1454,11 @@ Sizzle.contains = function( context, elem ) { if ( ( context.ownerDocument || context ) != document ) { setDocument( context ); } - return contains( context, elem ); + return jQuery.contains( context, elem ); }; -Sizzle.attr = function( elem, name ) { + +find.attr = function( elem, name ) { // Set document vars if needed // Support: IE 11+, Edge 17 - 18+ @@ -1655,25 +1471,19 @@ Sizzle.attr = function( elem, name ) { var fn = Expr.attrHandle[ name.toLowerCase() ], - // Don't get fooled by Object.prototype properties (jQuery #13807) + // Don't get fooled by Object.prototype properties (see trac-13807) val = fn && hasOwn.call( Expr.attrHandle, name.toLowerCase() ) ? fn( elem, name, !documentIsHTML ) : undefined; - return val !== undefined ? - val : - support.attributes || !documentIsHTML ? - elem.getAttribute( name ) : - ( val = elem.getAttributeNode( name ) ) && val.specified ? - val.value : - null; -}; + if ( val !== undefined ) { + return val; + } -Sizzle.escape = function( sel ) { - return ( sel + "" ).replace( rcssescape, fcssescape ); + return elem.getAttribute( name ); }; -Sizzle.error = function( msg ) { +find.error = function( msg ) { throw new Error( "Syntax error, unrecognized expression: " + msg ); }; @@ -1681,16 +1491,20 @@ Sizzle.error = function( msg ) { * Document sorting and removing duplicates * @param {ArrayLike} results */ -Sizzle.uniqueSort = function( results ) { +jQuery.uniqueSort = function( results ) { var elem, duplicates = [], j = 0, i = 0; // Unless we *know* we can detect duplicates, assume their presence - hasDuplicate = !support.detectDuplicates; - sortInput = !support.sortStable && results.slice( 0 ); - results.sort( sortOrder ); + // + // Support: Android <=4.0+ + // Testing for detecting duplicates is unpredictable so instead assume we can't + // depend on duplicate detection in all browsers without a stable sort. + hasDuplicate = !support.sortStable; + sortInput = !support.sortStable && slice.call( results, 0 ); + sort.call( results, sortOrder ); if ( hasDuplicate ) { while ( ( elem = results[ i++ ] ) ) { @@ -1698,59 +1512,23 @@ Sizzle.uniqueSort = function( results ) { j = duplicates.push( i ); } } - while ( j-- ) { - results.splice( duplicates[ j ], 1 ); - } - } - - // Clear input after sorting to release objects - // See https://github.com/jquery/sizzle/pull/225 - sortInput = null; - - return results; -}; - -/** - * Utility function for retrieving the text value of an array of DOM nodes - * @param {Array|Element} elem - */ -getText = Sizzle.getText = function( elem ) { - var node, - ret = "", - i = 0, - nodeType = elem.nodeType; - - if ( !nodeType ) { - - // If no nodeType, this is expected to be an array - while ( ( node = elem[ i++ ] ) ) { - - // Do not traverse comment nodes - ret += getText( node ); - } - } else if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) { - - // Use textContent for elements - // innerText usage removed for consistency of new lines (jQuery #11153) - if ( typeof elem.textContent === "string" ) { - return elem.textContent; - } else { - - // Traverse its children - for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { - ret += getText( elem ); - } - } - } else if ( nodeType === 3 || nodeType === 4 ) { - return elem.nodeValue; + while ( j-- ) { + splice.call( results, duplicates[ j ], 1 ); + } } - // Do not include comment or processing instruction nodes + // Clear input after sorting to release objects + // See https://github.com/jquery/sizzle/pull/225 + sortInput = null; - return ret; + return results; +}; + +jQuery.fn.uniqueSort = function() { + return this.pushStack( jQuery.uniqueSort( slice.apply( this ) ) ); }; -Expr = Sizzle.selectors = { +Expr = jQuery.expr = { // Can be adjusted by the user cacheLength: 50, @@ -1771,12 +1549,12 @@ Expr = Sizzle.selectors = { }, preFilter: { - "ATTR": function( match ) { + ATTR: function( match ) { match[ 1 ] = match[ 1 ].replace( runescape, funescape ); // Move the given value to match[3] whether quoted or unquoted - match[ 3 ] = ( match[ 3 ] || match[ 4 ] || - match[ 5 ] || "" ).replace( runescape, funescape ); + match[ 3 ] = ( match[ 3 ] || match[ 4 ] || match[ 5 ] || "" ) + .replace( runescape, funescape ); if ( match[ 2 ] === "~=" ) { match[ 3 ] = " " + match[ 3 ] + " "; @@ -1785,7 +1563,7 @@ Expr = Sizzle.selectors = { return match.slice( 0, 4 ); }, - "CHILD": function( match ) { + CHILD: function( match ) { /* matches from matchExpr["CHILD"] 1 type (only|nth|...) @@ -1803,29 +1581,30 @@ Expr = Sizzle.selectors = { // nth-* requires argument if ( !match[ 3 ] ) { - Sizzle.error( match[ 0 ] ); + find.error( match[ 0 ] ); } // numeric x and y parameters for Expr.filter.CHILD // remember that false/true cast respectively to 0/1 match[ 4 ] = +( match[ 4 ] ? match[ 5 ] + ( match[ 6 ] || 1 ) : - 2 * ( match[ 3 ] === "even" || match[ 3 ] === "odd" ) ); + 2 * ( match[ 3 ] === "even" || match[ 3 ] === "odd" ) + ); match[ 5 ] = +( ( match[ 7 ] + match[ 8 ] ) || match[ 3 ] === "odd" ); - // other types prohibit arguments + // other types prohibit arguments } else if ( match[ 3 ] ) { - Sizzle.error( match[ 0 ] ); + find.error( match[ 0 ] ); } return match; }, - "PSEUDO": function( match ) { + PSEUDO: function( match ) { var excess, unquoted = !match[ 6 ] && match[ 2 ]; - if ( matchExpr[ "CHILD" ].test( match[ 0 ] ) ) { + if ( matchExpr.CHILD.test( match[ 0 ] ) ) { return null; } @@ -1854,36 +1633,36 @@ Expr = Sizzle.selectors = { filter: { - "TAG": function( nodeNameSelector ) { - var nodeName = nodeNameSelector.replace( runescape, funescape ).toLowerCase(); + TAG: function( nodeNameSelector ) { + var expectedNodeName = nodeNameSelector.replace( runescape, funescape ).toLowerCase(); return nodeNameSelector === "*" ? function() { return true; } : function( elem ) { - return elem.nodeName && elem.nodeName.toLowerCase() === nodeName; + return nodeName( elem, expectedNodeName ); }; }, - "CLASS": function( className ) { + CLASS: function( className ) { var pattern = classCache[ className + " " ]; return pattern || - ( pattern = new RegExp( "(^|" + whitespace + - ")" + className + "(" + whitespace + "|$)" ) ) && classCache( - className, function( elem ) { - return pattern.test( - typeof elem.className === "string" && elem.className || - typeof elem.getAttribute !== "undefined" && - elem.getAttribute( "class" ) || - "" - ); + ( pattern = new RegExp( "(^|" + whitespace + ")" + className + + "(" + whitespace + "|$)" ) ) && + classCache( className, function( elem ) { + return pattern.test( + typeof elem.className === "string" && elem.className || + typeof elem.getAttribute !== "undefined" && + elem.getAttribute( "class" ) || + "" + ); } ); }, - "ATTR": function( name, operator, check ) { + ATTR: function( name, operator, check ) { return function( elem ) { - var result = Sizzle.attr( elem, name ); + var result = find.attr( elem, name ); if ( result == null ) { return operator === "!="; @@ -1894,22 +1673,34 @@ Expr = Sizzle.selectors = { result += ""; - /* eslint-disable max-len */ - - return operator === "=" ? result === check : - operator === "!=" ? result !== check : - operator === "^=" ? check && result.indexOf( check ) === 0 : - operator === "*=" ? check && result.indexOf( check ) > -1 : - operator === "$=" ? check && result.slice( -check.length ) === check : - operator === "~=" ? ( " " + result.replace( rwhitespace, " " ) + " " ).indexOf( check ) > -1 : - operator === "|=" ? result === check || result.slice( 0, check.length + 1 ) === check + "-" : - false; - /* eslint-enable max-len */ + if ( operator === "=" ) { + return result === check; + } + if ( operator === "!=" ) { + return result !== check; + } + if ( operator === "^=" ) { + return check && result.indexOf( check ) === 0; + } + if ( operator === "*=" ) { + return check && result.indexOf( check ) > -1; + } + if ( operator === "$=" ) { + return check && result.slice( -check.length ) === check; + } + if ( operator === "~=" ) { + return ( " " + result.replace( rwhitespace, " " ) + " " ) + .indexOf( check ) > -1; + } + if ( operator === "|=" ) { + return result === check || result.slice( 0, check.length + 1 ) === check + "-"; + } + return false; }; }, - "CHILD": function( type, what, _argument, first, last ) { + CHILD: function( type, what, _argument, first, last ) { var simple = type.slice( 0, 3 ) !== "nth", forward = type.slice( -4 ) !== "last", ofType = what === "of-type"; @@ -1922,7 +1713,7 @@ Expr = Sizzle.selectors = { } : function( elem, _context, xml ) { - var cache, uniqueCache, outerCache, node, nodeIndex, start, + var cache, outerCache, node, nodeIndex, start, dir = simple !== forward ? "nextSibling" : "previousSibling", parent = elem.parentNode, name = ofType && elem.nodeName.toLowerCase(), @@ -1937,7 +1728,7 @@ Expr = Sizzle.selectors = { node = elem; while ( ( node = node[ dir ] ) ) { if ( ofType ? - node.nodeName.toLowerCase() === name : + nodeName( node, name ) : node.nodeType === 1 ) { return false; @@ -1956,17 +1747,8 @@ Expr = Sizzle.selectors = { if ( forward && useCache ) { // Seek `elem` from a previously-cached index - - // ...in a gzip-friendly way - node = parent; - outerCache = node[ expando ] || ( node[ expando ] = {} ); - - // Support: IE <9 only - // Defend against cloned attroperties (jQuery gh-1709) - uniqueCache = outerCache[ node.uniqueID ] || - ( outerCache[ node.uniqueID ] = {} ); - - cache = uniqueCache[ type ] || []; + outerCache = parent[ expando ] || ( parent[ expando ] = {} ); + cache = outerCache[ type ] || []; nodeIndex = cache[ 0 ] === dirruns && cache[ 1 ]; diff = nodeIndex && cache[ 2 ]; node = nodeIndex && parent.childNodes[ nodeIndex ]; @@ -1978,7 +1760,7 @@ Expr = Sizzle.selectors = { // When found, cache indexes on `parent` and break if ( node.nodeType === 1 && ++diff && node === elem ) { - uniqueCache[ type ] = [ dirruns, nodeIndex, diff ]; + outerCache[ type ] = [ dirruns, nodeIndex, diff ]; break; } } @@ -1987,17 +1769,8 @@ Expr = Sizzle.selectors = { // Use previously-cached element index if available if ( useCache ) { - - // ...in a gzip-friendly way - node = elem; - outerCache = node[ expando ] || ( node[ expando ] = {} ); - - // Support: IE <9 only - // Defend against cloned attroperties (jQuery gh-1709) - uniqueCache = outerCache[ node.uniqueID ] || - ( outerCache[ node.uniqueID ] = {} ); - - cache = uniqueCache[ type ] || []; + outerCache = elem[ expando ] || ( elem[ expando ] = {} ); + cache = outerCache[ type ] || []; nodeIndex = cache[ 0 ] === dirruns && cache[ 1 ]; diff = nodeIndex; } @@ -2011,7 +1784,7 @@ Expr = Sizzle.selectors = { ( diff = nodeIndex = 0 ) || start.pop() ) ) { if ( ( ofType ? - node.nodeName.toLowerCase() === name : + nodeName( node, name ) : node.nodeType === 1 ) && ++diff ) { @@ -2019,13 +1792,7 @@ Expr = Sizzle.selectors = { if ( useCache ) { outerCache = node[ expando ] || ( node[ expando ] = {} ); - - // Support: IE <9 only - // Defend against cloned attroperties (jQuery gh-1709) - uniqueCache = outerCache[ node.uniqueID ] || - ( outerCache[ node.uniqueID ] = {} ); - - uniqueCache[ type ] = [ dirruns, diff ]; + outerCache[ type ] = [ dirruns, diff ]; } if ( node === elem ) { @@ -2043,19 +1810,19 @@ Expr = Sizzle.selectors = { }; }, - "PSEUDO": function( pseudo, argument ) { + PSEUDO: function( pseudo, argument ) { // pseudo-class names are case-insensitive - // http://www.w3.org/TR/selectors/#pseudo-classes + // https://www.w3.org/TR/selectors/#pseudo-classes // Prioritize by case sensitivity in case custom pseudos are added with uppercase letters // Remember that setFilters inherits from pseudos var args, fn = Expr.pseudos[ pseudo ] || Expr.setFilters[ pseudo.toLowerCase() ] || - Sizzle.error( "unsupported pseudo: " + pseudo ); + find.error( "unsupported pseudo: " + pseudo ); // The user may use createPseudo to indicate that // arguments are needed to create the filter function - // just as Sizzle does + // just as jQuery does if ( fn[ expando ] ) { return fn( argument ); } @@ -2069,7 +1836,7 @@ Expr = Sizzle.selectors = { matched = fn( seed, argument ), i = matched.length; while ( i-- ) { - idx = indexOf( seed, matched[ i ] ); + idx = indexOf.call( seed, matched[ i ] ); seed[ idx ] = !( matches[ idx ] = matched[ i ] ); } } ) : @@ -2085,14 +1852,14 @@ Expr = Sizzle.selectors = { pseudos: { // Potentially complex pseudos - "not": markFunction( function( selector ) { + not: markFunction( function( selector ) { // Trim the selector passed to compile // to avoid treating leading and trailing // spaces as combinators var input = [], results = [], - matcher = compile( selector.replace( rtrim, "$1" ) ); + matcher = compile( selector.replace( rtrimCSS, "$1" ) ); return matcher[ expando ] ? markFunction( function( seed, matches, _context, xml ) { @@ -2111,22 +1878,23 @@ Expr = Sizzle.selectors = { input[ 0 ] = elem; matcher( input, null, xml, results ); - // Don't keep the element (issue #299) + // Don't keep the element + // (see https://github.com/jquery/sizzle/issues/299) input[ 0 ] = null; return !results.pop(); }; } ), - "has": markFunction( function( selector ) { + has: markFunction( function( selector ) { return function( elem ) { - return Sizzle( selector, elem ).length > 0; + return find( selector, elem ).length > 0; }; } ), - "contains": markFunction( function( text ) { + contains: markFunction( function( text ) { text = text.replace( runescape, funescape ); return function( elem ) { - return ( elem.textContent || getText( elem ) ).indexOf( text ) > -1; + return ( elem.textContent || jQuery.text( elem ) ).indexOf( text ) > -1; }; } ), @@ -2136,12 +1904,12 @@ Expr = Sizzle.selectors = { // or beginning with the identifier C immediately followed by "-". // The matching of C against the element's language value is performed case-insensitively. // The identifier C does not have to be a valid language name." - // http://www.w3.org/TR/selectors/#lang-pseudo - "lang": markFunction( function( lang ) { + // https://www.w3.org/TR/selectors/#lang-pseudo + lang: markFunction( function( lang ) { // lang value must be a valid identifier if ( !ridentifier.test( lang || "" ) ) { - Sizzle.error( "unsupported lang: " + lang ); + find.error( "unsupported lang: " + lang ); } lang = lang.replace( runescape, funescape ).toLowerCase(); return function( elem ) { @@ -2160,38 +1928,39 @@ Expr = Sizzle.selectors = { } ), // Miscellaneous - "target": function( elem ) { + target: function( elem ) { var hash = window.location && window.location.hash; return hash && hash.slice( 1 ) === elem.id; }, - "root": function( elem ) { - return elem === docElem; + root: function( elem ) { + return elem === documentElement; }, - "focus": function( elem ) { - return elem === document.activeElement && - ( !document.hasFocus || document.hasFocus() ) && + focus: function( elem ) { + return elem === safeActiveElement() && + document.hasFocus() && !!( elem.type || elem.href || ~elem.tabIndex ); }, // Boolean properties - "enabled": createDisabledPseudo( false ), - "disabled": createDisabledPseudo( true ), + enabled: createDisabledPseudo( false ), + disabled: createDisabledPseudo( true ), - "checked": function( elem ) { + checked: function( elem ) { // In CSS3, :checked should return both checked and selected elements - // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked - var nodeName = elem.nodeName.toLowerCase(); - return ( nodeName === "input" && !!elem.checked ) || - ( nodeName === "option" && !!elem.selected ); + // https://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked + return ( nodeName( elem, "input" ) && !!elem.checked ) || + ( nodeName( elem, "option" ) && !!elem.selected ); }, - "selected": function( elem ) { + selected: function( elem ) { - // Accessing this property makes selected-by-default - // options in Safari work properly + // Support: IE <=11+ + // Accessing the selectedIndex property + // forces the browser to treat the default option as + // selected when in an optgroup. if ( elem.parentNode ) { // eslint-disable-next-line no-unused-expressions elem.parentNode.selectedIndex; @@ -2201,9 +1970,9 @@ Expr = Sizzle.selectors = { }, // Contents - "empty": function( elem ) { + empty: function( elem ) { - // http://www.w3.org/TR/selectors/#empty-pseudo + // https://www.w3.org/TR/selectors/#empty-pseudo // :empty is negated by element (1) or content nodes (text: 3; cdata: 4; entity ref: 5), // but not by others (comment: 8; processing instruction: 7; etc.) // nodeType < 6 works because attributes (2) do not appear as children @@ -2215,49 +1984,49 @@ Expr = Sizzle.selectors = { return true; }, - "parent": function( elem ) { - return !Expr.pseudos[ "empty" ]( elem ); + parent: function( elem ) { + return !Expr.pseudos.empty( elem ); }, // Element/input types - "header": function( elem ) { + header: function( elem ) { return rheader.test( elem.nodeName ); }, - "input": function( elem ) { + input: function( elem ) { return rinputs.test( elem.nodeName ); }, - "button": function( elem ) { - var name = elem.nodeName.toLowerCase(); - return name === "input" && elem.type === "button" || name === "button"; + button: function( elem ) { + return nodeName( elem, "input" ) && elem.type === "button" || + nodeName( elem, "button" ); }, - "text": function( elem ) { + text: function( elem ) { var attr; - return elem.nodeName.toLowerCase() === "input" && - elem.type === "text" && + return nodeName( elem, "input" ) && elem.type === "text" && - // Support: IE<8 - // New HTML5 attribute values (e.g., "search") appear with elem.type === "text" + // Support: IE <10 only + // New HTML5 attribute values (e.g., "search") appear + // with elem.type === "text" ( ( attr = elem.getAttribute( "type" ) ) == null || attr.toLowerCase() === "text" ); }, // Position-in-collection - "first": createPositionalPseudo( function() { + first: createPositionalPseudo( function() { return [ 0 ]; } ), - "last": createPositionalPseudo( function( _matchIndexes, length ) { + last: createPositionalPseudo( function( _matchIndexes, length ) { return [ length - 1 ]; } ), - "eq": createPositionalPseudo( function( _matchIndexes, length, argument ) { + eq: createPositionalPseudo( function( _matchIndexes, length, argument ) { return [ argument < 0 ? argument + length : argument ]; } ), - "even": createPositionalPseudo( function( matchIndexes, length ) { + even: createPositionalPseudo( function( matchIndexes, length ) { var i = 0; for ( ; i < length; i += 2 ) { matchIndexes.push( i ); @@ -2265,7 +2034,7 @@ Expr = Sizzle.selectors = { return matchIndexes; } ), - "odd": createPositionalPseudo( function( matchIndexes, length ) { + odd: createPositionalPseudo( function( matchIndexes, length ) { var i = 1; for ( ; i < length; i += 2 ) { matchIndexes.push( i ); @@ -2273,19 +2042,24 @@ Expr = Sizzle.selectors = { return matchIndexes; } ), - "lt": createPositionalPseudo( function( matchIndexes, length, argument ) { - var i = argument < 0 ? - argument + length : - argument > length ? - length : - argument; + lt: createPositionalPseudo( function( matchIndexes, length, argument ) { + var i; + + if ( argument < 0 ) { + i = argument + length; + } else if ( argument > length ) { + i = length; + } else { + i = argument; + } + for ( ; --i >= 0; ) { matchIndexes.push( i ); } return matchIndexes; } ), - "gt": createPositionalPseudo( function( matchIndexes, length, argument ) { + gt: createPositionalPseudo( function( matchIndexes, length, argument ) { var i = argument < 0 ? argument + length : argument; for ( ; ++i < length; ) { matchIndexes.push( i ); @@ -2295,7 +2069,7 @@ Expr = Sizzle.selectors = { } }; -Expr.pseudos[ "nth" ] = Expr.pseudos[ "eq" ]; +Expr.pseudos.nth = Expr.pseudos.eq; // Add button/input type pseudos for ( i in { radio: true, checkbox: true, file: true, password: true, image: true } ) { @@ -2310,7 +2084,7 @@ function setFilters() {} setFilters.prototype = Expr.filters = Expr.pseudos; Expr.setFilters = new setFilters(); -tokenize = Sizzle.tokenize = function( selector, parseOnly ) { +function tokenize( selector, parseOnly ) { var matched, match, tokens, type, soFar, groups, preFilters, cached = tokenCache[ selector + " " ]; @@ -2338,13 +2112,13 @@ tokenize = Sizzle.tokenize = function( selector, parseOnly ) { matched = false; // Combinators - if ( ( match = rcombinators.exec( soFar ) ) ) { + if ( ( match = rleadingCombinator.exec( soFar ) ) ) { matched = match.shift(); tokens.push( { value: matched, // Cast descendant combinators to space - type: match[ 0 ].replace( rtrim, " " ) + type: match[ 0 ].replace( rtrimCSS, " " ) } ); soFar = soFar.slice( matched.length ); } @@ -2371,14 +2145,16 @@ tokenize = Sizzle.tokenize = function( selector, parseOnly ) { // Return the length of the invalid excess // if we're just parsing // Otherwise, throw an error or return tokens - return parseOnly ? - soFar.length : - soFar ? - Sizzle.error( selector ) : + if ( parseOnly ) { + return soFar.length; + } - // Cache the tokens - tokenCache( selector, groups ).slice( 0 ); -}; + return soFar ? + find.error( selector ) : + + // Cache the tokens + tokenCache( selector, groups ).slice( 0 ); +} function toSelector( tokens ) { var i = 0, @@ -2411,7 +2187,7 @@ function addCombinator( matcher, combinator, base ) { // Check against all ancestor/preceding elements function( elem, context, xml ) { - var oldCache, uniqueCache, outerCache, + var oldCache, outerCache, newCache = [ dirruns, doneName ]; // We can't set arbitrary data on XML nodes, so they don't benefit from combinator caching @@ -2428,14 +2204,9 @@ function addCombinator( matcher, combinator, base ) { if ( elem.nodeType === 1 || checkNonElements ) { outerCache = elem[ expando ] || ( elem[ expando ] = {} ); - // Support: IE <9 only - // Defend against cloned attroperties (jQuery gh-1709) - uniqueCache = outerCache[ elem.uniqueID ] || - ( outerCache[ elem.uniqueID ] = {} ); - - if ( skip && skip === elem.nodeName.toLowerCase() ) { + if ( skip && nodeName( elem, skip ) ) { elem = elem[ dir ] || elem; - } else if ( ( oldCache = uniqueCache[ key ] ) && + } else if ( ( oldCache = outerCache[ key ] ) && oldCache[ 0 ] === dirruns && oldCache[ 1 ] === doneName ) { // Assign to newCache so results back-propagate to previous elements @@ -2443,7 +2214,7 @@ function addCombinator( matcher, combinator, base ) { } else { // Reuse newcache so results back-propagate to previous elements - uniqueCache[ key ] = newCache; + outerCache[ key ] = newCache; // A match means we're done; a fail means we have to keep checking if ( ( newCache[ 2 ] = matcher( elem, context, xml ) ) ) { @@ -2475,7 +2246,7 @@ function multipleContexts( selector, contexts, results ) { var i = 0, len = contexts.length; for ( ; i < len; i++ ) { - Sizzle( selector, contexts[ i ], results ); + find( selector, contexts[ i ], results ); } return results; } @@ -2509,38 +2280,37 @@ function setMatcher( preFilter, selector, matcher, postFilter, postFinder, postS postFinder = setMatcher( postFinder, postSelector ); } return markFunction( function( seed, results, context, xml ) { - var temp, i, elem, + var temp, i, elem, matcherOut, preMap = [], postMap = [], preexisting = results.length, // Get initial elements from seed or context - elems = seed || multipleContexts( - selector || "*", - context.nodeType ? [ context ] : context, - [] - ), + elems = seed || + multipleContexts( selector || "*", + context.nodeType ? [ context ] : context, [] ), // Prefilter to get matcher input, preserving a map for seed-results synchronization matcherIn = preFilter && ( seed || !selector ) ? condense( elems, preMap, preFilter, context, xml ) : - elems, + elems; - matcherOut = matcher ? + if ( matcher ) { - // If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results, - postFinder || ( seed ? preFilter : preexisting || postFilter ) ? + // If we have a postFinder, or filtered seed, or non-seed postFilter + // or preexisting results, + matcherOut = postFinder || ( seed ? preFilter : preexisting || postFilter ) ? - // ...intermediate processing is necessary - [] : + // ...intermediate processing is necessary + [] : - // ...otherwise use results directly - results : - matcherIn; + // ...otherwise use results directly + results; - // Find primary matches - if ( matcher ) { + // Find primary matches matcher( matcherIn, matcherOut, context, xml ); + } else { + matcherOut = matcherIn; } // Apply postFilter @@ -2578,7 +2348,7 @@ function setMatcher( preFilter, selector, matcher, postFilter, postFinder, postS i = matcherOut.length; while ( i-- ) { if ( ( elem = matcherOut[ i ] ) && - ( temp = postFinder ? indexOf( seed, elem ) : preMap[ i ] ) > -1 ) { + ( temp = postFinder ? indexOf.call( seed, elem ) : preMap[ i ] ) > -1 ) { seed[ temp ] = !( results[ temp ] = elem ); } @@ -2613,15 +2383,21 @@ function matcherFromTokens( tokens ) { return elem === checkContext; }, implicitRelative, true ), matchAnyContext = addCombinator( function( elem ) { - return indexOf( checkContext, elem ) > -1; + return indexOf.call( checkContext, elem ) > -1; }, implicitRelative, true ), matchers = [ function( elem, context, xml ) { - var ret = ( !leadingRelative && ( xml || context !== outermostContext ) ) || ( + + // Support: IE 11+, Edge 17 - 18+ + // IE/Edge sometimes throw a "Permission denied" error when strict-comparing + // two documents; shallow comparisons work. + // eslint-disable-next-line eqeqeq + var ret = ( !leadingRelative && ( xml || context != outermostContext ) ) || ( ( checkContext = context ).nodeType ? matchContext( elem, context, xml ) : matchAnyContext( elem, context, xml ) ); - // Avoid hanging onto element (issue #299) + // Avoid hanging onto element + // (see https://github.com/jquery/sizzle/issues/299) checkContext = null; return ret; } ]; @@ -2646,11 +2422,10 @@ function matcherFromTokens( tokens ) { i > 1 && elementMatcher( matchers ), i > 1 && toSelector( - // If the preceding token was a descendant combinator, insert an implicit any-element `*` - tokens - .slice( 0, i - 1 ) - .concat( { value: tokens[ i - 2 ].type === " " ? "*" : "" } ) - ).replace( rtrim, "$1" ), + // If the preceding token was a descendant combinator, insert an implicit any-element `*` + tokens.slice( 0, i - 1 ) + .concat( { value: tokens[ i - 2 ].type === " " ? "*" : "" } ) + ).replace( rtrimCSS, "$1" ), matcher, i < j && matcherFromTokens( tokens.slice( i, j ) ), j < len && matcherFromTokens( ( tokens = tokens.slice( j ) ) ), @@ -2676,7 +2451,7 @@ function matcherFromGroupMatchers( elementMatchers, setMatchers ) { contextBackup = outermostContext, // We must always have either seed elements or outermost context - elems = seed || byElement && Expr.find[ "TAG" ]( "*", outermost ), + elems = seed || byElement && Expr.find.TAG( "*", outermost ), // Use integer dirruns iff this is the outermost matcher dirrunsUnique = ( dirruns += contextBackup == null ? 1 : Math.random() || 0.1 ), @@ -2692,8 +2467,9 @@ function matcherFromGroupMatchers( elementMatchers, setMatchers ) { } // Add elements passing elementMatchers directly to results - // Support: IE<9, Safari - // Tolerate NodeList properties (IE: "length"; Safari: ) matching elements by id + // Support: iOS <=7 - 9 only + // Tolerate NodeList properties (IE: "length"; Safari: ) matching + // elements by id. (see trac-14142) for ( ; i !== len && ( elem = elems[ i ] ) != null; i++ ) { if ( byElement && elem ) { j = 0; @@ -2708,7 +2484,7 @@ function matcherFromGroupMatchers( elementMatchers, setMatchers ) { } while ( ( matcher = elementMatchers[ j++ ] ) ) { if ( matcher( elem, context || document, xml ) ) { - results.push( elem ); + push.call( results, elem ); break; } } @@ -2771,7 +2547,7 @@ function matcherFromGroupMatchers( elementMatchers, setMatchers ) { if ( outermost && !seed && setMatched.length > 0 && ( matchedCount + setMatchers.length ) > 1 ) { - Sizzle.uniqueSort( results ); + jQuery.uniqueSort( results ); } } @@ -2789,7 +2565,7 @@ function matcherFromGroupMatchers( elementMatchers, setMatchers ) { superMatcher; } -compile = Sizzle.compile = function( selector, match /* Internal Use Only */ ) { +function compile( selector, match /* Internal Use Only */ ) { var i, setMatchers = [], elementMatchers = [], @@ -2812,27 +2588,25 @@ compile = Sizzle.compile = function( selector, match /* Internal Use Only */ ) { } // Cache the compiled function - cached = compilerCache( - selector, - matcherFromGroupMatchers( elementMatchers, setMatchers ) - ); + cached = compilerCache( selector, + matcherFromGroupMatchers( elementMatchers, setMatchers ) ); // Save selector and tokenization cached.selector = selector; } return cached; -}; +} /** - * A low-level selection function that works with Sizzle's compiled + * A low-level selection function that works with jQuery's compiled * selector functions * @param {String|Function} selector A selector or a pre-compiled - * selector function built with Sizzle.compile + * selector function built with jQuery selector compile * @param {Element} context * @param {Array} [results] * @param {Array} [seed] A set of elements to match against */ -select = Sizzle.select = function( selector, context, results, seed ) { +function select( selector, context, results, seed ) { var i, tokens, token, type, find, compiled = typeof selector === "function" && selector, match = !seed && tokenize( ( selector = compiled.selector || selector ) ); @@ -2846,10 +2620,12 @@ select = Sizzle.select = function( selector, context, results, seed ) { // Reduce context if the leading compound selector is an ID tokens = match[ 0 ] = match[ 0 ].slice( 0 ); if ( tokens.length > 2 && ( token = tokens[ 0 ] ).type === "ID" && - context.nodeType === 9 && documentIsHTML && Expr.relative[ tokens[ 1 ].type ] ) { + context.nodeType === 9 && documentIsHTML && Expr.relative[ tokens[ 1 ].type ] ) { - context = ( Expr.find[ "ID" ]( token.matches[ 0 ] - .replace( runescape, funescape ), context ) || [] )[ 0 ]; + context = ( Expr.find.ID( + token.matches[ 0 ].replace( runescape, funescape ), + context + ) || [] )[ 0 ]; if ( !context ) { return results; @@ -2862,7 +2638,7 @@ select = Sizzle.select = function( selector, context, results, seed ) { } // Fetch a seed set for right-to-left matching - i = matchExpr[ "needsContext" ].test( selector ) ? 0 : tokens.length; + i = matchExpr.needsContext.test( selector ) ? 0 : tokens.length; while ( i-- ) { token = tokens[ i ]; @@ -2875,8 +2651,8 @@ select = Sizzle.select = function( selector, context, results, seed ) { // Search, expanding context for leading sibling combinators if ( ( seed = find( token.matches[ 0 ].replace( runescape, funescape ), - rsibling.test( tokens[ 0 ].type ) && testContext( context.parentNode ) || - context + rsibling.test( tokens[ 0 ].type ) && + testContext( context.parentNode ) || context ) ) ) { // If seed is empty or no tokens remain, we can return early @@ -2903,21 +2679,18 @@ select = Sizzle.select = function( selector, context, results, seed ) { !context || rsibling.test( selector ) && testContext( context.parentNode ) || context ); return results; -}; +} // One-time assignments +// Support: Android <=4.0 - 4.1+ // Sort stability support.sortStable = expando.split( "" ).sort( sortOrder ).join( "" ) === expando; -// Support: Chrome 14-35+ -// Always assume duplicates if they aren't passed to the comparison function -support.detectDuplicates = !!hasDuplicate; - // Initialize against the default document setDocument(); -// Support: Webkit<537.32 - Safari 6.0.3/Chrome 25 (fixed in Chrome 27) +// Support: Android <=4.0 - 4.1+ // Detached nodes confoundingly follow *each other* support.sortDetached = assert( function( el ) { @@ -2925,68 +2698,29 @@ support.sortDetached = assert( function( el ) { return el.compareDocumentPosition( document.createElement( "fieldset" ) ) & 1; } ); -// Support: IE<8 -// Prevent attribute/property "interpolation" -// https://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx -if ( !assert( function( el ) { - el.innerHTML = ""; - return el.firstChild.getAttribute( "href" ) === "#"; -} ) ) { - addHandle( "type|href|height|width", function( elem, name, isXML ) { - if ( !isXML ) { - return elem.getAttribute( name, name.toLowerCase() === "type" ? 1 : 2 ); - } - } ); -} - -// Support: IE<9 -// Use defaultValue in place of getAttribute("value") -if ( !support.attributes || !assert( function( el ) { - el.innerHTML = ""; - el.firstChild.setAttribute( "value", "" ); - return el.firstChild.getAttribute( "value" ) === ""; -} ) ) { - addHandle( "value", function( elem, _name, isXML ) { - if ( !isXML && elem.nodeName.toLowerCase() === "input" ) { - return elem.defaultValue; - } - } ); -} - -// Support: IE<9 -// Use getAttributeNode to fetch booleans when getAttribute lies -if ( !assert( function( el ) { - return el.getAttribute( "disabled" ) == null; -} ) ) { - addHandle( booleans, function( elem, name, isXML ) { - var val; - if ( !isXML ) { - return elem[ name ] === true ? name.toLowerCase() : - ( val = elem.getAttributeNode( name ) ) && val.specified ? - val.value : - null; - } - } ); -} - -return Sizzle; - -} )( window ); - - - -jQuery.find = Sizzle; -jQuery.expr = Sizzle.selectors; +jQuery.find = find; // Deprecated jQuery.expr[ ":" ] = jQuery.expr.pseudos; -jQuery.uniqueSort = jQuery.unique = Sizzle.uniqueSort; -jQuery.text = Sizzle.getText; -jQuery.isXMLDoc = Sizzle.isXML; -jQuery.contains = Sizzle.contains; -jQuery.escapeSelector = Sizzle.escape; +jQuery.unique = jQuery.uniqueSort; + +// These have always been private, but they used to be documented as part of +// Sizzle so let's maintain them for now for backwards compatibility purposes. +find.compile = compile; +find.select = select; +find.setDocument = setDocument; +find.tokenize = tokenize; +find.escape = jQuery.escapeSelector; +find.getText = jQuery.text; +find.isXML = jQuery.isXMLDoc; +find.selectors = jQuery.expr; +find.support = jQuery.support; +find.uniqueSort = jQuery.uniqueSort; + /* eslint-enable */ + +} )(); var dir = function( elem, dir, until ) { @@ -3020,13 +2754,6 @@ var siblings = function( n, elem ) { var rneedsContext = jQuery.expr.match.needsContext; - - -function nodeName( elem, name ) { - - return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase(); - -}; var rsingleTag = ( /^<([a-z][^\/\0>:\x20\t\r\n\f]*)[\x20\t\r\n\f]*\/?>(?:<\/\1>|)$/i ); @@ -3125,8 +2852,8 @@ jQuery.fn.extend( { var rootjQuery, // A simple way to check for HTML strings - // Prioritize #id over to avoid XSS via location.hash (#9521) - // Strict HTML recognition (#11290: must start with <) + // Prioritize #id over to avoid XSS via location.hash (trac-9521) + // Strict HTML recognition (trac-11290: must start with <) // Shortcut simple #id case for speed rquickExpr = /^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]+))$/, @@ -3277,7 +3004,7 @@ jQuery.fn.extend( { if ( cur.nodeType < 11 && ( targets ? targets.index( cur ) > -1 : - // Don't pass non-elements to Sizzle + // Don't pass non-elements to jQuery#find cur.nodeType === 1 && jQuery.find.matchesSelector( cur, selectors ) ) ) { @@ -3832,7 +3559,7 @@ jQuery.extend( { if ( jQuery.Deferred.exceptionHook ) { jQuery.Deferred.exceptionHook( e, - process.stackTrace ); + process.error ); } // Support: Promises/A+ section 2.3.3.3.4.1 @@ -3860,10 +3587,17 @@ jQuery.extend( { process(); } else { - // Call an optional hook to record the stack, in case of exception + // Call an optional hook to record the error, in case of exception // since it's otherwise lost when execution goes async - if ( jQuery.Deferred.getStackHook ) { - process.stackTrace = jQuery.Deferred.getStackHook(); + if ( jQuery.Deferred.getErrorHook ) { + process.error = jQuery.Deferred.getErrorHook(); + + // The deprecated alias of the above. While the name suggests + // returning the stack, not an error instance, jQuery just passes + // it directly to `console.warn` so both will work; an instance + // just better cooperates with source maps. + } else if ( jQuery.Deferred.getStackHook ) { + process.error = jQuery.Deferred.getStackHook(); } window.setTimeout( process ); } @@ -3997,8 +3731,8 @@ jQuery.extend( { resolveContexts = Array( i ), resolveValues = slice.call( arguments ), - // the master Deferred - master = jQuery.Deferred(), + // the primary Deferred + primary = jQuery.Deferred(), // subordinate callback factory updateFunc = function( i ) { @@ -4006,30 +3740,30 @@ jQuery.extend( { resolveContexts[ i ] = this; resolveValues[ i ] = arguments.length > 1 ? slice.call( arguments ) : value; if ( !( --remaining ) ) { - master.resolveWith( resolveContexts, resolveValues ); + primary.resolveWith( resolveContexts, resolveValues ); } }; }; // Single- and empty arguments are adopted like Promise.resolve if ( remaining <= 1 ) { - adoptValue( singleValue, master.done( updateFunc( i ) ).resolve, master.reject, + adoptValue( singleValue, primary.done( updateFunc( i ) ).resolve, primary.reject, !remaining ); // Use .then() to unwrap secondary thenables (cf. gh-3000) - if ( master.state() === "pending" || + if ( primary.state() === "pending" || isFunction( resolveValues[ i ] && resolveValues[ i ].then ) ) { - return master.then(); + return primary.then(); } } // Multiple arguments are aggregated like Promise.all array elements while ( i-- ) { - adoptValue( resolveValues[ i ], updateFunc( i ), master.reject ); + adoptValue( resolveValues[ i ], updateFunc( i ), primary.reject ); } - return master.promise(); + return primary.promise(); } } ); @@ -4038,12 +3772,16 @@ jQuery.extend( { // warn about them ASAP rather than swallowing them by default. var rerrorNames = /^(Eval|Internal|Range|Reference|Syntax|Type|URI)Error$/; -jQuery.Deferred.exceptionHook = function( error, stack ) { +// If `jQuery.Deferred.getErrorHook` is defined, `asyncError` is an error +// captured before the async barrier to get the original error cause +// which may otherwise be hidden. +jQuery.Deferred.exceptionHook = function( error, asyncError ) { // Support: IE 8 - 9 only // Console exists when dev tools are open, which can happen at any time if ( window.console && window.console.warn && error && rerrorNames.test( error.name ) ) { - window.console.warn( "jQuery.Deferred exception: " + error.message, error.stack, stack ); + window.console.warn( "jQuery.Deferred exception: " + error.message, + error.stack, asyncError ); } }; @@ -4083,7 +3821,7 @@ jQuery.extend( { isReady: false, // A counter to track how many items to wait for before - // the ready event fires. See #6781 + // the ready event fires. See trac-6781 readyWait: 1, // Handle when the DOM is ready @@ -4180,8 +3918,8 @@ var access = function( elems, fn, key, value, chainable, emptyGet, raw ) { for ( ; i < len; i++ ) { fn( elems[ i ], key, raw ? - value : - value.call( elems[ i ], i, fn( elems[ i ], key ) ) + value : + value.call( elems[ i ], i, fn( elems[ i ], key ) ) ); } } @@ -4211,7 +3949,7 @@ function fcamelCase( _all, letter ) { // Convert dashed to camelCase; used by the css and data modules // Support: IE <=9 - 11, Edge 12 - 15 -// Microsoft forgot to hump their vendor prefix (#9572) +// Microsoft forgot to hump their vendor prefix (trac-9572) function camelCase( string ) { return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase ); } @@ -4247,7 +3985,7 @@ Data.prototype = { value = {}; // We can accept data for non-element nodes in modern browsers, - // but we should not, see #8335. + // but we should not, see trac-8335. // Always return an empty object. if ( acceptData( owner ) ) { @@ -4486,7 +4224,7 @@ jQuery.fn.extend( { while ( i-- ) { // Support: IE 11 only - // The attrs elements can be null (#14894) + // The attrs elements can be null (trac-14894) if ( attrs[ i ] ) { name = attrs[ i ].name; if ( name.indexOf( "data-" ) === 0 ) { @@ -4909,9 +4647,9 @@ var rscriptType = ( /^$|^module$|\/(?:java|ecma)script/i ); input = document.createElement( "input" ); // Support: Android 4.0 - 4.3 only - // Check state lost if the name is set (#11217) + // Check state lost if the name is set (trac-11217) // Support: Windows Web Apps (WWA) - // `name` and `type` must use .setAttribute for WWA (#14901) + // `name` and `type` must use .setAttribute for WWA (trac-14901) input.setAttribute( "type", "radio" ); input.setAttribute( "checked", "checked" ); input.setAttribute( "name", "t" ); @@ -4935,7 +4673,7 @@ var rscriptType = ( /^$|^module$|\/(?:java|ecma)script/i ); } )(); -// We have to close these tags to support XHTML (#13200) +// We have to close these tags to support XHTML (trac-13200) var wrapMap = { // XHTML parsers do not magically insert elements in the @@ -4961,7 +4699,7 @@ if ( !support.option ) { function getAll( context, tag ) { // Support: IE <=9 - 11 only - // Use typeof to avoid zero-argument method invocation on host objects (#15151) + // Use typeof to avoid zero-argument method invocation on host objects (trac-15151) var ret; if ( typeof context.getElementsByTagName !== "undefined" ) { @@ -5044,7 +4782,7 @@ function buildFragment( elems, context, scripts, selection, ignored ) { // Remember the top-level container tmp = fragment.firstChild; - // Ensure the created nodes are orphaned (#12392) + // Ensure the created nodes are orphaned (trac-12392) tmp.textContent = ""; } } @@ -5089,10 +4827,7 @@ function buildFragment( elems, context, scripts, selection, ignored ) { } -var - rkeyEvent = /^key/, - rmouseEvent = /^(?:mouse|pointer|contextmenu|drag|drop)|click/, - rtypenamespace = /^([^.]*)(?:\.(.+)|)/; +var rtypenamespace = /^([^.]*)(?:\.(.+)|)/; function returnTrue() { return true; @@ -5102,25 +4837,6 @@ function returnFalse() { return false; } -// Support: IE <=9 - 11+ -// focus() and blur() are asynchronous, except when they are no-op. -// So expect focus to be synchronous when the element is already active, -// and blur to be synchronous when the element is not already active. -// (focus and blur are always synchronous in other supported browsers, -// this just defines when we can count on it). -function expectSync( elem, type ) { - return ( elem === safeActiveElement() ) === ( type === "focus" ); -} - -// Support: IE <=9 only -// Accessing document.activeElement can throw unexpectedly -// https://bugs.jquery.com/ticket/13393 -function safeActiveElement() { - try { - return document.activeElement; - } catch ( err ) { } -} - function on( elem, types, selector, data, fn, one ) { var origFn, type; @@ -5387,8 +5103,8 @@ jQuery.event = { event = jQuery.event.fix( nativeEvent ), handlers = ( - dataPriv.get( this, "events" ) || Object.create( null ) - )[ event.type ] || [], + dataPriv.get( this, "events" ) || Object.create( null ) + )[ event.type ] || [], special = jQuery.event.special[ event.type ] || {}; // Use the fix-ed jQuery.Event rather than the (read-only) native event @@ -5468,15 +5184,15 @@ jQuery.event = { for ( ; cur !== this; cur = cur.parentNode || this ) { - // Don't check non-elements (#13208) - // Don't process clicks on disabled elements (#6911, #8165, #11382, #11764) + // Don't check non-elements (trac-13208) + // Don't process clicks on disabled elements (trac-6911, trac-8165, trac-11382, trac-11764) if ( cur.nodeType === 1 && !( event.type === "click" && cur.disabled === true ) ) { matchedHandlers = []; matchedSelectors = {}; for ( i = 0; i < delegateCount; i++ ) { handleObj = handlers[ i ]; - // Don't conflict with Object.prototype properties (#13203) + // Don't conflict with Object.prototype properties (trac-13203) sel = handleObj.selector + " "; if ( matchedSelectors[ sel ] === undefined ) { @@ -5512,12 +5228,12 @@ jQuery.event = { get: isFunction( hook ) ? function() { if ( this.originalEvent ) { - return hook( this.originalEvent ); + return hook( this.originalEvent ); } } : function() { if ( this.originalEvent ) { - return this.originalEvent[ name ]; + return this.originalEvent[ name ]; } }, @@ -5558,7 +5274,7 @@ jQuery.event = { el.click && nodeName( el, "input" ) ) { // dataPriv.set( el, "click", ... ) - leverageNative( el, "click", returnTrue ); + leverageNative( el, "click", true ); } // Return false to allow normal processing in the caller @@ -5609,10 +5325,10 @@ jQuery.event = { // synthetic events by interrupting progress until reinvoked in response to // *native* events that it fires directly, ensuring that state changes have // already occurred before other listeners are invoked. -function leverageNative( el, type, expectSync ) { +function leverageNative( el, type, isSetup ) { - // Missing expectSync indicates a trigger call, which must force setup through jQuery.event.add - if ( !expectSync ) { + // Missing `isSetup` indicates a trigger call, which must force setup through jQuery.event.add + if ( !isSetup ) { if ( dataPriv.get( el, type ) === undefined ) { jQuery.event.add( el, type, returnTrue ); } @@ -5624,15 +5340,13 @@ function leverageNative( el, type, expectSync ) { jQuery.event.add( el, type, { namespace: false, handler: function( event ) { - var notAsync, result, + var result, saved = dataPriv.get( this, type ); if ( ( event.isTrigger & 1 ) && this[ type ] ) { // Interrupt processing of the outer synthetic .trigger()ed event - // Saved data should be false in such cases, but might be a leftover capture object - // from an async native handler (gh-4350) - if ( !saved.length ) { + if ( !saved ) { // Store arguments for use when handling the inner native event // There will always be at least one argument (an event object), so this array @@ -5641,27 +5355,22 @@ function leverageNative( el, type, expectSync ) { dataPriv.set( this, type, saved ); // Trigger the native event and capture its result - // Support: IE <=9 - 11+ - // focus() and blur() are asynchronous - notAsync = expectSync( this, type ); this[ type ](); result = dataPriv.get( this, type ); - if ( saved !== result || notAsync ) { - dataPriv.set( this, type, false ); - } else { - result = {}; - } + dataPriv.set( this, type, false ); + if ( saved !== result ) { // Cancel the outer synthetic event event.stopImmediatePropagation(); event.preventDefault(); - return result.value; + + return result; } // If this is an inner synthetic event for an event with a bubbling surrogate - // (focus or blur), assume that the surrogate already propagated from triggering the - // native event and prevent that from happening again here. + // (focus or blur), assume that the surrogate already propagated from triggering + // the native event and prevent that from happening again here. // This technically gets the ordering wrong w.r.t. to `.trigger()` (in which the // bubbling surrogate propagates *after* the non-bubbling base), but that seems // less bad than duplication. @@ -5671,22 +5380,25 @@ function leverageNative( el, type, expectSync ) { // If this is a native event triggered above, everything is now in order // Fire an inner synthetic event with the original arguments - } else if ( saved.length ) { + } else if ( saved ) { // ...and capture the result - dataPriv.set( this, type, { - value: jQuery.event.trigger( - - // Support: IE <=9 - 11+ - // Extend with the prototype to reset the above stopImmediatePropagation() - jQuery.extend( saved[ 0 ], jQuery.Event.prototype ), - saved.slice( 1 ), - this - ) - } ); - - // Abort handling of the native event - event.stopImmediatePropagation(); + dataPriv.set( this, type, jQuery.event.trigger( + saved[ 0 ], + saved.slice( 1 ), + this + ) ); + + // Abort handling of the native event by all jQuery handlers while allowing + // native handlers on the same element to run. On target, this is achieved + // by stopping immediate propagation just on the jQuery event. However, + // the native event is re-wrapped by a jQuery one on each level of the + // propagation so the only way to stop it for jQuery is to stop it for + // everyone via native `stopPropagation()`. This is not a problem for + // focus/blur which don't bubble, but it does also stop click on checkboxes + // and radios. We accept this limitation. + event.stopPropagation(); + event.isImmediatePropagationStopped = returnTrue; } } } ); @@ -5724,7 +5436,7 @@ jQuery.Event = function( src, props ) { // Create target properties // Support: Safari <=6 - 7 only - // Target should not be a text node (#504, #13143) + // Target should not be a text node (trac-504, trac-13143) this.target = ( src.target && src.target.nodeType === 3 ) ? src.target.parentNode : src.target; @@ -5821,49 +5533,77 @@ jQuery.each( { targetTouches: true, toElement: true, touches: true, + which: true +}, jQuery.event.addProp ); - which: function( event ) { - var button = event.button; - - // Add which for key events - if ( event.which == null && rkeyEvent.test( event.type ) ) { - return event.charCode != null ? event.charCode : event.keyCode; - } - - // Add which for click: 1 === left; 2 === middle; 3 === right - if ( !event.which && button !== undefined && rmouseEvent.test( event.type ) ) { - if ( button & 1 ) { - return 1; - } +jQuery.each( { focus: "focusin", blur: "focusout" }, function( type, delegateType ) { - if ( button & 2 ) { - return 3; - } + function focusMappedHandler( nativeEvent ) { + if ( document.documentMode ) { - if ( button & 4 ) { - return 2; + // Support: IE 11+ + // Attach a single focusin/focusout handler on the document while someone wants + // focus/blur. This is because the former are synchronous in IE while the latter + // are async. In other browsers, all those handlers are invoked synchronously. + + // `handle` from private data would already wrap the event, but we need + // to change the `type` here. + var handle = dataPriv.get( this, "handle" ), + event = jQuery.event.fix( nativeEvent ); + event.type = nativeEvent.type === "focusin" ? "focus" : "blur"; + event.isSimulated = true; + + // First, handle focusin/focusout + handle( nativeEvent ); + + // ...then, handle focus/blur + // + // focus/blur don't bubble while focusin/focusout do; simulate the former by only + // invoking the handler at the lower level. + if ( event.target === event.currentTarget ) { + + // The setup part calls `leverageNative`, which, in turn, calls + // `jQuery.event.add`, so event handle will already have been set + // by this point. + handle( event ); } + } else { - return 0; + // For non-IE browsers, attach a single capturing handler on the document + // while someone wants focusin/focusout. + jQuery.event.simulate( delegateType, nativeEvent.target, + jQuery.event.fix( nativeEvent ) ); } - - return event.which; } -}, jQuery.event.addProp ); -jQuery.each( { focus: "focusin", blur: "focusout" }, function( type, delegateType ) { jQuery.event.special[ type ] = { // Utilize native event if possible so blur/focus sequence is correct setup: function() { + var attaches; + // Claim the first handler // dataPriv.set( this, "focus", ... ) // dataPriv.set( this, "blur", ... ) - leverageNative( this, type, expectSync ); + leverageNative( this, type, true ); - // Return false to allow normal processing in the caller - return false; + if ( document.documentMode ) { + + // Support: IE 9 - 11+ + // We use the same native handler for focusin & focus (and focusout & blur) + // so we need to coordinate setup & teardown parts between those events. + // Use `delegateType` as the key as `type` is already used by `leverageNative`. + attaches = dataPriv.get( this, delegateType ); + if ( !attaches ) { + this.addEventListener( delegateType, focusMappedHandler ); + } + dataPriv.set( this, delegateType, ( attaches || 0 ) + 1 ); + } else { + + // Return false to allow normal processing in the caller + return false; + } }, trigger: function() { @@ -5874,8 +5614,84 @@ jQuery.each( { focus: "focusin", blur: "focusout" }, function( type, delegateTyp return true; }, + teardown: function() { + var attaches; + + if ( document.documentMode ) { + attaches = dataPriv.get( this, delegateType ) - 1; + if ( !attaches ) { + this.removeEventListener( delegateType, focusMappedHandler ); + dataPriv.remove( this, delegateType ); + } else { + dataPriv.set( this, delegateType, attaches ); + } + } else { + + // Return false to indicate standard teardown should be applied + return false; + } + }, + + // Suppress native focus or blur if we're currently inside + // a leveraged native-event stack + _default: function( event ) { + return dataPriv.get( event.target, type ); + }, + delegateType: delegateType }; + + // Support: Firefox <=44 + // Firefox doesn't have focus(in | out) events + // Related ticket - https://bugzilla.mozilla.org/show_bug.cgi?id=687787 + // + // Support: Chrome <=48 - 49, Safari <=9.0 - 9.1 + // focus(in | out) events fire after focus & blur events, + // which is spec violation - http://www.w3.org/TR/DOM-Level-3-Events/#events-focusevent-event-order + // Related ticket - https://bugs.chromium.org/p/chromium/issues/detail?id=449857 + // + // Support: IE 9 - 11+ + // To preserve relative focusin/focus & focusout/blur event order guaranteed on the 3.x branch, + // attach a single handler for both events in IE. + jQuery.event.special[ delegateType ] = { + setup: function() { + + // Handle: regular nodes (via `this.ownerDocument`), window + // (via `this.document`) & document (via `this`). + var doc = this.ownerDocument || this.document || this, + dataHolder = document.documentMode ? this : doc, + attaches = dataPriv.get( dataHolder, delegateType ); + + // Support: IE 9 - 11+ + // We use the same native handler for focusin & focus (and focusout & blur) + // so we need to coordinate setup & teardown parts between those events. + // Use `delegateType` as the key as `type` is already used by `leverageNative`. + if ( !attaches ) { + if ( document.documentMode ) { + this.addEventListener( delegateType, focusMappedHandler ); + } else { + doc.addEventListener( type, focusMappedHandler, true ); + } + } + dataPriv.set( dataHolder, delegateType, ( attaches || 0 ) + 1 ); + }, + teardown: function() { + var doc = this.ownerDocument || this.document || this, + dataHolder = document.documentMode ? this : doc, + attaches = dataPriv.get( dataHolder, delegateType ) - 1; + + if ( !attaches ) { + if ( document.documentMode ) { + this.removeEventListener( delegateType, focusMappedHandler ); + } else { + doc.removeEventListener( type, focusMappedHandler, true ); + } + dataPriv.remove( dataHolder, delegateType ); + } else { + dataPriv.set( dataHolder, delegateType, attaches ); + } + } + }; } ); // Create mouseenter/leave events using mouseover/out and event-time checks @@ -5970,7 +5786,8 @@ var // checked="checked" or checked rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i, - rcleanScript = /^\s*\s*$/g; + + rcleanScript = /^\s*\s*$/g; // Prefer a tbody over its parent table for containing new rows function manipulationTarget( elem, content ) { @@ -6084,7 +5901,7 @@ function domManip( collection, args, callback, ignored ) { // Use the original fragment for the last item // instead of the first because it can end up - // being emptied incorrectly in certain situations (#8070). + // being emptied incorrectly in certain situations (trac-8070). for ( ; i < l; i++ ) { node = fragment; @@ -6106,7 +5923,7 @@ function domManip( collection, args, callback, ignored ) { if ( hasScripts ) { doc = scripts[ scripts.length - 1 ].ownerDocument; - // Reenable scripts + // Re-enable scripts jQuery.map( scripts, restoreScript ); // Evaluate executable scripts on first document insertion @@ -6125,6 +5942,12 @@ function domManip( collection, args, callback, ignored ) { }, doc ); } } else { + + // Unwrap a CDATA section containing script contents. This shouldn't be + // needed as in XML documents they're already not visible when + // inspecting element contents and in HTML documents they have no + // meaning but we're preserving that logic for backwards compatibility. + // This will be removed completely in 4.0. See gh-4904. DOMEval( node.textContent.replace( rcleanScript, "" ), node, doc ); } } @@ -6171,7 +5994,8 @@ jQuery.extend( { if ( !support.noCloneChecked && ( elem.nodeType === 1 || elem.nodeType === 11 ) && !jQuery.isXMLDoc( elem ) ) { - // We eschew Sizzle here for performance reasons: https://jsperf.com/getall-vs-sizzle/2 + // We eschew jQuery#find here for performance reasons: + // https://jsperf.com/getall-vs-sizzle/2 destElements = getAll( clone ); srcElements = getAll( elem ); @@ -6407,9 +6231,12 @@ jQuery.each( { } ); var rnumnonpx = new RegExp( "^(" + pnum + ")(?!px)[a-z%]+$", "i" ); +var rcustomProp = /^--/; + + var getStyles = function( elem ) { - // Support: IE <=11 only, Firefox <=30 (#15098, #14150) + // Support: IE <=11 only, Firefox <=30 (trac-15098, trac-14150) // IE throws on elements created in popups // FF meanwhile throws on frame elements through "defaultView.getComputedStyle" var view = elem.ownerDocument.defaultView; @@ -6509,7 +6336,7 @@ var rboxStyle = new RegExp( cssExpand.join( "|" ), "i" ); } // Support: IE <=9 - 11 only - // Style of cloned element affects source element cloned (#8908) + // Style of cloned element affects source element cloned (trac-8908) div.style.backgroundClip = "content-box"; div.cloneNode( true ).style.backgroundClip = ""; support.clearCloneStyle = div.style.backgroundClip === "content-box"; @@ -6541,6 +6368,10 @@ var rboxStyle = new RegExp( cssExpand.join( "|" ), "i" ); // set in CSS while `offset*` properties report correct values. // Behavior in IE 9 is more subtle than in newer versions & it passes // some versions of this test; make sure not to make it pass there! + // + // Support: Firefox 70+ + // Only Firefox includes border widths + // in computed dimensions. (gh-4529) reliableTrDimensions: function() { var table, tr, trChild, trStyle; if ( reliableTrDimensionsVal == null ) { @@ -6548,17 +6379,32 @@ var rboxStyle = new RegExp( cssExpand.join( "|" ), "i" ); tr = document.createElement( "tr" ); trChild = document.createElement( "div" ); - table.style.cssText = "position:absolute;left:-11111px"; + table.style.cssText = "position:absolute;left:-11111px;border-collapse:separate"; + tr.style.cssText = "box-sizing:content-box;border:1px solid"; + + // Support: Chrome 86+ + // Height set through cssText does not get applied. + // Computed height then comes back as 0. tr.style.height = "1px"; trChild.style.height = "9px"; + // Support: Android 8 Chrome 86+ + // In our bodyBackground.html iframe, + // display for all div elements is set to "inline", + // which causes a problem only in Android 8 Chrome 86. + // Ensuring the div is `display: block` + // gets around this issue. + trChild.style.display = "block"; + documentElement .appendChild( table ) .appendChild( tr ) .appendChild( trChild ); trStyle = window.getComputedStyle( tr ); - reliableTrDimensionsVal = parseInt( trStyle.height ) > 3; + reliableTrDimensionsVal = ( parseInt( trStyle.height, 10 ) + + parseInt( trStyle.borderTopWidth, 10 ) + + parseInt( trStyle.borderBottomWidth, 10 ) ) === tr.offsetHeight; documentElement.removeChild( table ); } @@ -6570,6 +6416,7 @@ var rboxStyle = new RegExp( cssExpand.join( "|" ), "i" ); function curCSS( elem, name, computed ) { var width, minWidth, maxWidth, ret, + isCustomProp = rcustomProp.test( name ), // Support: Firefox 51+ // Retrieving style before computed somehow @@ -6580,11 +6427,42 @@ function curCSS( elem, name, computed ) { computed = computed || getStyles( elem ); // getPropertyValue is needed for: - // .css('filter') (IE 9 only, #12537) - // .css('--customProperty) (#3144) + // .css('filter') (IE 9 only, trac-12537) + // .css('--customProperty) (gh-3144) if ( computed ) { + + // Support: IE <=9 - 11+ + // IE only supports `"float"` in `getPropertyValue`; in computed styles + // it's only available as `"cssFloat"`. We no longer modify properties + // sent to `.css()` apart from camelCasing, so we need to check both. + // Normally, this would create difference in behavior: if + // `getPropertyValue` returns an empty string, the value returned + // by `.css()` would be `undefined`. This is usually the case for + // disconnected elements. However, in IE even disconnected elements + // with no styles return `"none"` for `getPropertyValue( "float" )` ret = computed.getPropertyValue( name ) || computed[ name ]; + if ( isCustomProp && ret ) { + + // Support: Firefox 105+, Chrome <=105+ + // Spec requires trimming whitespace for custom properties (gh-4926). + // Firefox only trims leading whitespace. Chrome just collapses + // both leading & trailing whitespace to a single space. + // + // Fall back to `undefined` if empty string returned. + // This collapses a missing definition with property defined + // and set to an empty string but there's no standard API + // allowing us to differentiate them without a performance penalty + // and returning `undefined` aligns with older jQuery. + // + // rtrimCSS treats U+000D CARRIAGE RETURN and U+000C FORM FEED + // as whitespace while CSS does not, but this is not a problem + // because CSS preprocessing replaces them with U+000A LINE FEED + // (which *is* CSS whitespace) + // https://www.w3.org/TR/css-syntax-3/#input-preprocessing + ret = ret.replace( rtrimCSS, "$1" ) || undefined; + } + if ( ret === "" && !isAttached( elem ) ) { ret = jQuery.style( elem, name ); } @@ -6680,7 +6558,6 @@ var // except "table", "table-cell", or "table-caption" // See here for display values: https://developer.mozilla.org/en-US/docs/CSS/display rdisplayswap = /^(none|table(?!-c[ea]).+)/, - rcustomProp = /^--/, cssShow = { position: "absolute", visibility: "hidden", display: "block" }, cssNormalTransform = { letterSpacing: "0", @@ -6702,7 +6579,8 @@ function setPositiveNumber( _elem, value, subtract ) { function boxModelAdjustment( elem, dimension, box, isBorderBox, styles, computedVal ) { var i = dimension === "width" ? 1 : 0, extra = 0, - delta = 0; + delta = 0, + marginDelta = 0; // Adjustment may not be necessary if ( box === ( isBorderBox ? "border" : "content" ) ) { @@ -6712,8 +6590,10 @@ function boxModelAdjustment( elem, dimension, box, isBorderBox, styles, computed for ( ; i < 4; i += 2 ) { // Both box models exclude margin + // Count margin delta separately to only add it after scroll gutter adjustment. + // This is needed to make negative margins work with `outerHeight( true )` (gh-3982). if ( box === "margin" ) { - delta += jQuery.css( elem, box + cssExpand[ i ], true, styles ); + marginDelta += jQuery.css( elem, box + cssExpand[ i ], true, styles ); } // If we get here with a content-box, we're seeking "padding" or "border" or "margin" @@ -6764,7 +6644,7 @@ function boxModelAdjustment( elem, dimension, box, isBorderBox, styles, computed ) ) || 0; } - return delta; + return delta + marginDelta; } function getWidthOrHeight( elem, dimension, extra ) { @@ -6862,26 +6742,35 @@ jQuery.extend( { // Don't automatically add "px" to these possibly-unitless properties cssNumber: { - "animationIterationCount": true, - "columnCount": true, - "fillOpacity": true, - "flexGrow": true, - "flexShrink": true, - "fontWeight": true, - "gridArea": true, - "gridColumn": true, - "gridColumnEnd": true, - "gridColumnStart": true, - "gridRow": true, - "gridRowEnd": true, - "gridRowStart": true, - "lineHeight": true, - "opacity": true, - "order": true, - "orphans": true, - "widows": true, - "zIndex": true, - "zoom": true + animationIterationCount: true, + aspectRatio: true, + borderImageSlice: true, + columnCount: true, + flexGrow: true, + flexShrink: true, + fontWeight: true, + gridArea: true, + gridColumn: true, + gridColumnEnd: true, + gridColumnStart: true, + gridRow: true, + gridRowEnd: true, + gridRowStart: true, + lineHeight: true, + opacity: true, + order: true, + orphans: true, + scale: true, + widows: true, + zIndex: true, + zoom: true, + + // SVG-related + fillOpacity: true, + floodOpacity: true, + stopOpacity: true, + strokeMiterlimit: true, + strokeOpacity: true }, // Add in properties whose names you wish to fix before @@ -6916,15 +6805,15 @@ jQuery.extend( { if ( value !== undefined ) { type = typeof value; - // Convert "+=" or "-=" to relative numbers (#7345) + // Convert "+=" or "-=" to relative numbers (trac-7345) if ( type === "string" && ( ret = rcssNum.exec( value ) ) && ret[ 1 ] ) { value = adjustCSS( elem, name, ret ); - // Fixes bug #9237 + // Fixes bug trac-9237 type = "number"; } - // Make sure that null and NaN values aren't set (#7116) + // Make sure that null and NaN values aren't set (trac-7116) if ( value == null || value !== value ) { return; } @@ -7022,10 +6911,10 @@ jQuery.each( [ "height", "width" ], function( _i, dimension ) { // Running getBoundingClientRect on a disconnected node // in IE throws an error. ( !elem.getClientRects().length || !elem.getBoundingClientRect().width ) ? - swap( elem, cssShow, function() { - return getWidthOrHeight( elem, dimension, extra ); - } ) : - getWidthOrHeight( elem, dimension, extra ); + swap( elem, cssShow, function() { + return getWidthOrHeight( elem, dimension, extra ); + } ) : + getWidthOrHeight( elem, dimension, extra ); } }, @@ -7084,7 +6973,7 @@ jQuery.cssHooks.marginLeft = addGetHookIf( support.reliableMarginLeft, swap( elem, { marginLeft: 0 }, function() { return elem.getBoundingClientRect().left; } ) - ) + "px"; + ) + "px"; } } ); @@ -7223,7 +7112,7 @@ Tween.propHooks = { if ( jQuery.fx.step[ tween.prop ] ) { jQuery.fx.step[ tween.prop ]( tween ); } else if ( tween.elem.nodeType === 1 && ( - jQuery.cssHooks[ tween.prop ] || + jQuery.cssHooks[ tween.prop ] || tween.elem.style[ finalPropName( tween.prop ) ] != null ) ) { jQuery.style( tween.elem, tween.prop, tween.now + tween.unit ); } else { @@ -7468,7 +7357,7 @@ function defaultPrefilter( elem, props, opts ) { anim.done( function() { - /* eslint-enable no-loop-func */ + /* eslint-enable no-loop-func */ // The final step of a "hide" animation is actually hiding the element if ( !hidden ) { @@ -7548,7 +7437,7 @@ function Animation( elem, properties, options ) { remaining = Math.max( 0, animation.startTime + animation.duration - currentTime ), // Support: Android 2.3 only - // Archaic crash bug won't allow us to use `1 - ( 0.5 || 0 )` (#12497) + // Archaic crash bug won't allow us to use `1 - ( 0.5 || 0 )` (trac-12497) temp = remaining / animation.duration || 0, percent = 1 - temp, index = 0, @@ -7588,7 +7477,7 @@ function Animation( elem, properties, options ) { tweens: [], createTween: function( prop, end ) { var tween = jQuery.Tween( elem, animation.opts, prop, end, - animation.opts.specialEasing[ prop ] || animation.opts.easing ); + animation.opts.specialEasing[ prop ] || animation.opts.easing ); animation.tweens.push( tween ); return tween; }, @@ -7761,7 +7650,8 @@ jQuery.fn.extend( { anim.stop( true ); } }; - doAnimation.finish = doAnimation; + + doAnimation.finish = doAnimation; return empty || optall.queue === false ? this.each( doAnimation ) : @@ -7937,7 +7827,6 @@ jQuery.fx.speeds = { // Based off of the plugin by Clint Helfers, with permission. -// https://web.archive.org/web/20100324014747/http://blindsignals.com/index.php/2009/07/jquery-delay/ jQuery.fn.delay = function( time, type ) { time = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time; type = type || "fx"; @@ -8162,8 +8051,7 @@ jQuery.extend( { // Support: IE <=9 - 11 only // elem.tabIndex doesn't always return the // correct value when it hasn't been explicitly set - // https://web.archive.org/web/20141116233347/http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/ - // Use proper attribute retrieval(#12072) + // Use proper attribute retrieval (trac-12072) var tabindex = jQuery.find.attr( elem, "tabindex" ); if ( tabindex ) { @@ -8267,8 +8155,7 @@ function classesToArray( value ) { jQuery.fn.extend( { addClass: function( value ) { - var classes, elem, cur, curValue, clazz, j, finalValue, - i = 0; + var classNames, cur, curValue, className, i, finalValue; if ( isFunction( value ) ) { return this.each( function( j ) { @@ -8276,36 +8163,35 @@ jQuery.fn.extend( { } ); } - classes = classesToArray( value ); + classNames = classesToArray( value ); - if ( classes.length ) { - while ( ( elem = this[ i++ ] ) ) { - curValue = getClass( elem ); - cur = elem.nodeType === 1 && ( " " + stripAndCollapse( curValue ) + " " ); + if ( classNames.length ) { + return this.each( function() { + curValue = getClass( this ); + cur = this.nodeType === 1 && ( " " + stripAndCollapse( curValue ) + " " ); if ( cur ) { - j = 0; - while ( ( clazz = classes[ j++ ] ) ) { - if ( cur.indexOf( " " + clazz + " " ) < 0 ) { - cur += clazz + " "; + for ( i = 0; i < classNames.length; i++ ) { + className = classNames[ i ]; + if ( cur.indexOf( " " + className + " " ) < 0 ) { + cur += className + " "; } } // Only assign if different to avoid unneeded rendering. finalValue = stripAndCollapse( cur ); if ( curValue !== finalValue ) { - elem.setAttribute( "class", finalValue ); + this.setAttribute( "class", finalValue ); } } - } + } ); } return this; }, removeClass: function( value ) { - var classes, elem, cur, curValue, clazz, j, finalValue, - i = 0; + var classNames, cur, curValue, className, i, finalValue; if ( isFunction( value ) ) { return this.each( function( j ) { @@ -8317,45 +8203,42 @@ jQuery.fn.extend( { return this.attr( "class", "" ); } - classes = classesToArray( value ); + classNames = classesToArray( value ); - if ( classes.length ) { - while ( ( elem = this[ i++ ] ) ) { - curValue = getClass( elem ); + if ( classNames.length ) { + return this.each( function() { + curValue = getClass( this ); // This expression is here for better compressibility (see addClass) - cur = elem.nodeType === 1 && ( " " + stripAndCollapse( curValue ) + " " ); + cur = this.nodeType === 1 && ( " " + stripAndCollapse( curValue ) + " " ); if ( cur ) { - j = 0; - while ( ( clazz = classes[ j++ ] ) ) { + for ( i = 0; i < classNames.length; i++ ) { + className = classNames[ i ]; // Remove *all* instances - while ( cur.indexOf( " " + clazz + " " ) > -1 ) { - cur = cur.replace( " " + clazz + " ", " " ); + while ( cur.indexOf( " " + className + " " ) > -1 ) { + cur = cur.replace( " " + className + " ", " " ); } } // Only assign if different to avoid unneeded rendering. finalValue = stripAndCollapse( cur ); if ( curValue !== finalValue ) { - elem.setAttribute( "class", finalValue ); + this.setAttribute( "class", finalValue ); } } - } + } ); } return this; }, toggleClass: function( value, stateVal ) { - var type = typeof value, + var classNames, className, i, self, + type = typeof value, isValidValue = type === "string" || Array.isArray( value ); - if ( typeof stateVal === "boolean" && isValidValue ) { - return stateVal ? this.addClass( value ) : this.removeClass( value ); - } - if ( isFunction( value ) ) { return this.each( function( i ) { jQuery( this ).toggleClass( @@ -8365,17 +8248,20 @@ jQuery.fn.extend( { } ); } - return this.each( function() { - var className, i, self, classNames; + if ( typeof stateVal === "boolean" && isValidValue ) { + return stateVal ? this.addClass( value ) : this.removeClass( value ); + } + + classNames = classesToArray( value ); + return this.each( function() { if ( isValidValue ) { // Toggle individual class names - i = 0; self = jQuery( this ); - classNames = classesToArray( value ); - while ( ( className = classNames[ i++ ] ) ) { + for ( i = 0; i < classNames.length; i++ ) { + className = classNames[ i ]; // Check each className given, space separated list if ( self.hasClass( className ) ) { @@ -8401,8 +8287,8 @@ jQuery.fn.extend( { if ( this.setAttribute ) { this.setAttribute( "class", className || value === false ? - "" : - dataPriv.get( this, "__className__" ) || "" + "" : + dataPriv.get( this, "__className__" ) || "" ); } } @@ -8417,7 +8303,7 @@ jQuery.fn.extend( { while ( ( elem = this[ i++ ] ) ) { if ( elem.nodeType === 1 && ( " " + stripAndCollapse( getClass( elem ) ) + " " ).indexOf( className ) > -1 ) { - return true; + return true; } } @@ -8509,7 +8395,7 @@ jQuery.extend( { val : // Support: IE <=10 - 11 only - // option.text throws exceptions (#14686, #14858) + // option.text throws exceptions (trac-14686, trac-14858) // Strip and collapse whitespace // https://html.spec.whatwg.org/#strip-and-collapse-whitespace stripAndCollapse( jQuery.text( elem ) ); @@ -8536,7 +8422,7 @@ jQuery.extend( { option = options[ i ]; // Support: IE <=9 only - // IE8-9 doesn't update selected after form reset (#2551) + // IE8-9 doesn't update selected after form reset (trac-2551) if ( ( option.selected || i === index ) && // Don't return options that are disabled or in a disabled optgroup @@ -8610,9 +8496,39 @@ jQuery.each( [ "radio", "checkbox" ], function() { // Return jQuery for attributes-only inclusion +var location = window.location; + +var nonce = { guid: Date.now() }; + +var rquery = ( /\?/ ); + + + +// Cross-browser xml parsing +jQuery.parseXML = function( data ) { + var xml, parserErrorElem; + if ( !data || typeof data !== "string" ) { + return null; + } + // Support: IE 9 - 11 only + // IE throws on parseFromString with invalid input. + try { + xml = ( new window.DOMParser() ).parseFromString( data, "text/xml" ); + } catch ( e ) {} -support.focusin = "onfocusin" in window; + parserErrorElem = xml && xml.getElementsByTagName( "parsererror" )[ 0 ]; + if ( !xml || parserErrorElem ) { + jQuery.error( "Invalid XML: " + ( + parserErrorElem ? + jQuery.map( parserErrorElem.childNodes, function( el ) { + return el.textContent; + } ).join( "\n" ) : + data + ) ); + } + return xml; +}; var rfocusMorph = /^(?:focusinfocus|focusoutblur)$/, @@ -8679,8 +8595,8 @@ jQuery.extend( jQuery.event, { return; } - // Determine event propagation path in advance, per W3C events spec (#9951) - // Bubble up to document, then to window; watch for a global ownerDocument var (#9724) + // Determine event propagation path in advance, per W3C events spec (trac-9951) + // Bubble up to document, then to window; watch for a global ownerDocument var (trac-9724) if ( !onlyHandlers && !special.noBubble && !isWindow( elem ) ) { bubbleType = special.delegateType || type; @@ -8707,9 +8623,7 @@ jQuery.extend( jQuery.event, { special.bindType || type; // jQuery handler - handle = ( - dataPriv.get( cur, "events" ) || Object.create( null ) - )[ event.type ] && + handle = ( dataPriv.get( cur, "events" ) || Object.create( null ) )[ event.type ] && dataPriv.get( cur, "handle" ); if ( handle ) { handle.apply( cur, data ); @@ -8734,7 +8648,7 @@ jQuery.extend( jQuery.event, { acceptData( elem ) ) { // Call a native DOM method on the target with the same name as the event. - // Don't do default actions on window, that's where global variables be (#6170) + // Don't do default actions on window, that's where global variables be (trac-6170) if ( ontype && isFunction( elem[ type ] ) && !isWindow( elem ) ) { // Don't re-trigger an onFOO event when we call its FOO() method @@ -8802,80 +8716,6 @@ jQuery.fn.extend( { } ); -// Support: Firefox <=44 -// Firefox doesn't have focus(in | out) events -// Related ticket - https://bugzilla.mozilla.org/show_bug.cgi?id=687787 -// -// Support: Chrome <=48 - 49, Safari <=9.0 - 9.1 -// focus(in | out) events fire after focus & blur events, -// which is spec violation - http://www.w3.org/TR/DOM-Level-3-Events/#events-focusevent-event-order -// Related ticket - https://bugs.chromium.org/p/chromium/issues/detail?id=449857 -if ( !support.focusin ) { - jQuery.each( { focus: "focusin", blur: "focusout" }, function( orig, fix ) { - - // Attach a single capturing handler on the document while someone wants focusin/focusout - var handler = function( event ) { - jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ) ); - }; - - jQuery.event.special[ fix ] = { - setup: function() { - - // Handle: regular nodes (via `this.ownerDocument`), window - // (via `this.document`) & document (via `this`). - var doc = this.ownerDocument || this.document || this, - attaches = dataPriv.access( doc, fix ); - - if ( !attaches ) { - doc.addEventListener( orig, handler, true ); - } - dataPriv.access( doc, fix, ( attaches || 0 ) + 1 ); - }, - teardown: function() { - var doc = this.ownerDocument || this.document || this, - attaches = dataPriv.access( doc, fix ) - 1; - - if ( !attaches ) { - doc.removeEventListener( orig, handler, true ); - dataPriv.remove( doc, fix ); - - } else { - dataPriv.access( doc, fix, attaches ); - } - } - }; - } ); -} -var location = window.location; - -var nonce = { guid: Date.now() }; - -var rquery = ( /\?/ ); - - - -// Cross-browser xml parsing -jQuery.parseXML = function( data ) { - var xml; - if ( !data || typeof data !== "string" ) { - return null; - } - - // Support: IE 9 - 11 only - // IE throws on parseFromString with invalid input. - try { - xml = ( new window.DOMParser() ).parseFromString( data, "text/xml" ); - } catch ( e ) { - xml = undefined; - } - - if ( !xml || xml.getElementsByTagName( "parsererror" ).length ) { - jQuery.error( "Invalid XML: " + data ); - } - return xml; -}; - - var rbracket = /\[\]$/, rCRLF = /\r?\n/g, @@ -8971,16 +8811,14 @@ jQuery.fn.extend( { // Can add propHook for "elements" to filter or add form elements var elements = jQuery.prop( this, "elements" ); return elements ? jQuery.makeArray( elements ) : this; - } ) - .filter( function() { + } ).filter( function() { var type = this.type; // Use .is( ":disabled" ) so that fieldset[disabled] works return this.name && !jQuery( this ).is( ":disabled" ) && rsubmittable.test( this.nodeName ) && !rsubmitterTypes.test( type ) && ( this.checked || !rcheckableType.test( type ) ); - } ) - .map( function( _i, elem ) { + } ).map( function( _i, elem ) { var val = jQuery( this ).val(); if ( val == null ) { @@ -9005,7 +8843,7 @@ var rantiCache = /([?&])_=[^&]*/, rheaders = /^(.*?):[ \t]*([^\r\n]*)$/mg, - // #7653, #8125, #8152: local protocol detection + // trac-7653, trac-8125, trac-8152: local protocol detection rlocalProtocol = /^(?:about|app|app-storage|.+-extension|file|res|widget):$/, rnoContent = /^(?:GET|HEAD)$/, rprotocol = /^\/\//, @@ -9028,12 +8866,13 @@ var */ transports = {}, - // Avoid comment-prolog char sequence (#10098); must appease lint and evade compression + // Avoid comment-prolog char sequence (trac-10098); must appease lint and evade compression allTypes = "*/".concat( "*" ), // Anchor tag for parsing the document origin originAnchor = document.createElement( "a" ); - originAnchor.href = location.href; + +originAnchor.href = location.href; // Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport function addToPrefiltersOrTransports( structure ) { @@ -9098,7 +8937,7 @@ function inspectPrefiltersOrTransports( structure, options, originalOptions, jqX // A special extend for ajax options // that takes "flat" options (not to be deep extended) -// Fixes #9887 +// Fixes trac-9887 function ajaxExtend( target, src ) { var key, deep, flatOptions = jQuery.ajaxSettings.flatOptions || {}; @@ -9414,8 +9253,8 @@ jQuery.extend( { // Context for global events is callbackContext if it is a DOM node or jQuery collection globalEventContext = s.context && ( callbackContext.nodeType || callbackContext.jquery ) ? - jQuery( callbackContext ) : - jQuery.event, + jQuery( callbackContext ) : + jQuery.event, // Deferreds deferred = jQuery.Deferred(), @@ -9509,12 +9348,12 @@ jQuery.extend( { deferred.promise( jqXHR ); // Add protocol if not provided (prefilters might expect it) - // Handle falsy url in the settings object (#10093: consistency with old signature) + // Handle falsy url in the settings object (trac-10093: consistency with old signature) // We also use the url parameter if available s.url = ( ( url || s.url || location.href ) + "" ) .replace( rprotocol, location.protocol + "//" ); - // Alias method option to type as per ticket #12004 + // Alias method option to type as per ticket trac-12004 s.type = options.method || options.type || s.method || s.type; // Extract dataTypes list @@ -9557,7 +9396,7 @@ jQuery.extend( { } // We can fire global events as of now if asked to - // Don't fire events if jQuery.event is undefined in an AMD-usage scenario (#15118) + // Don't fire events if jQuery.event is undefined in an AMD-usage scenario (trac-15118) fireGlobals = jQuery.event && s.global; // Watch for a new set of requests @@ -9586,7 +9425,7 @@ jQuery.extend( { if ( s.data && ( s.processData || typeof s.data === "string" ) ) { cacheURL += ( rquery.test( cacheURL ) ? "&" : "?" ) + s.data; - // #9682: remove data so that it's not used in an eventual retry + // trac-9682: remove data so that it's not used in an eventual retry delete s.data; } @@ -9727,8 +9566,10 @@ jQuery.extend( { response = ajaxHandleResponses( s, jqXHR, responses ); } - // Use a noop converter for missing script - if ( !isSuccess && jQuery.inArray( "script", s.dataTypes ) > -1 ) { + // Use a noop converter for missing script but not if jsonp + if ( !isSuccess && + jQuery.inArray( "script", s.dataTypes ) > -1 && + jQuery.inArray( "json", s.dataTypes ) < 0 ) { s.converters[ "text script" ] = function() {}; } @@ -9857,7 +9698,7 @@ jQuery._evalUrl = function( url, options, doc ) { return jQuery.ajax( { url: url, - // Make this explicit, since user can override this through ajaxSetup (#11264) + // Make this explicit, since user can override this through ajaxSetup (trac-11264) type: "GET", dataType: "script", cache: true, @@ -9966,7 +9807,7 @@ var xhrSuccessStatus = { 0: 200, // Support: IE <=9 only - // #1450: sometimes IE returns 1223 when it should be 204 + // trac-1450: sometimes IE returns 1223 when it should be 204 1223: 204 }, xhrSupported = jQuery.ajaxSettings.xhr(); @@ -10038,7 +9879,7 @@ jQuery.ajaxTransport( function( options ) { } else { complete( - // File: protocol always yields status 0; see #8605, #14207 + // File: protocol always yields status 0; see trac-8605, trac-14207 xhr.status, xhr.statusText ); @@ -10099,7 +9940,7 @@ jQuery.ajaxTransport( function( options ) { xhr.send( options.hasContent && options.data || null ); } catch ( e ) { - // #14683: Only rethrow if this hasn't been notified as an error yet + // trac-14683: Only rethrow if this hasn't been notified as an error yet if ( callback ) { throw e; } @@ -10466,12 +10307,6 @@ jQuery.offset = { options.using.call( elem, props ); } else { - if ( typeof props.top === "number" ) { - props.top += "px"; - } - if ( typeof props.left === "number" ) { - props.left += "px"; - } curElem.css( props ); } } @@ -10640,8 +10475,11 @@ jQuery.each( [ "top", "left" ], function( _i, prop ) { // Create innerHeight, innerWidth, height, width, outerHeight and outerWidth methods jQuery.each( { Height: "height", Width: "width" }, function( name, type ) { - jQuery.each( { padding: "inner" + name, content: type, "": "outer" + name }, - function( defaultExtra, funcName ) { + jQuery.each( { + padding: "inner" + name, + content: type, + "": "outer" + name + }, function( defaultExtra, funcName ) { // Margin is only for outerHeight, outerWidth jQuery.fn[ funcName ] = function( margin, value ) { @@ -10722,11 +10560,14 @@ jQuery.fn.extend( { }, hover: function( fnOver, fnOut ) { - return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver ); + return this + .on( "mouseenter", fnOver ) + .on( "mouseleave", fnOut || fnOver ); } } ); -jQuery.each( ( "blur focus focusin focusout resize scroll click dblclick " + +jQuery.each( + ( "blur focus focusin focusout resize scroll click dblclick " + "mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " + "change select submit keydown keypress keyup contextmenu" ).split( " " ), function( _i, name ) { @@ -10737,14 +10578,17 @@ jQuery.each( ( "blur focus focusin focusout resize scroll click dblclick " + this.on( name, null, data, fn ) : this.trigger( name ); }; - } ); + } +); // Support: Android <=4.0 only // Make sure we trim BOM and NBSP -var rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g; +// Require that the "whitespace run" starts from a non-whitespace +// to avoid O(N^2) behavior when the engine would try matching "\s+$" at each space position. +var rtrim = /^[\s\uFEFF\xA0]+|([^\s\uFEFF\xA0])[\s\uFEFF\xA0]+$/g; // Bind a function to a context, optionally partially applying any // arguments. @@ -10811,7 +10655,7 @@ jQuery.isNumeric = function( obj ) { jQuery.trim = function( text ) { return text == null ? "" : - ( text + "" ).replace( rtrim, "" ); + ( text + "" ).replace( rtrim, "$1" ); }; @@ -10859,8 +10703,8 @@ jQuery.noConflict = function( deep ) { }; // Expose jQuery and $ identifiers, even in AMD -// (#7102#comment:10, https://github.com/jquery/jquery/pull/557) -// and CommonJS for browser emulators (#13566) +// (trac-7102#comment:10, https://github.com/jquery/jquery/pull/557) +// and CommonJS for browser emulators (trac-13566) if ( typeof noGlobal === "undefined" ) { window.jQuery = window.$ = jQuery; } diff --git a/DNN Platform/Website/Resources/Shared/scripts/jquery/jquery.min.js b/DNN Platform/Website/Resources/Shared/scripts/jquery/jquery.min.js index b0614034ad3..7f37b5d9912 100644 --- a/DNN Platform/Website/Resources/Shared/scripts/jquery/jquery.min.js +++ b/DNN Platform/Website/Resources/Shared/scripts/jquery/jquery.min.js @@ -1,2 +1,2 @@ -/*! jQuery v3.5.1 | (c) JS Foundation and other contributors | jquery.org/license */ -!function(e,t){"use strict";"object"==typeof module&&"object"==typeof module.exports?module.exports=e.document?t(e,!0):function(e){if(!e.document)throw new Error("jQuery requires a window with a document");return t(e)}:t(e)}("undefined"!=typeof window?window:this,function(C,e){"use strict";var t=[],r=Object.getPrototypeOf,s=t.slice,g=t.flat?function(e){return t.flat.call(e)}:function(e){return t.concat.apply([],e)},u=t.push,i=t.indexOf,n={},o=n.toString,v=n.hasOwnProperty,a=v.toString,l=a.call(Object),y={},m=function(e){return"function"==typeof e&&"number"!=typeof e.nodeType},x=function(e){return null!=e&&e===e.window},E=C.document,c={type:!0,src:!0,nonce:!0,noModule:!0};function b(e,t,n){var r,i,o=(n=n||E).createElement("script");if(o.text=e,t)for(r in c)(i=t[r]||t.getAttribute&&t.getAttribute(r))&&o.setAttribute(r,i);n.head.appendChild(o).parentNode.removeChild(o)}function w(e){return null==e?e+"":"object"==typeof e||"function"==typeof e?n[o.call(e)]||"object":typeof e}var f="3.5.1",S=function(e,t){return new S.fn.init(e,t)};function p(e){var t=!!e&&"length"in e&&e.length,n=w(e);return!m(e)&&!x(e)&&("array"===n||0===t||"number"==typeof t&&0+~]|"+M+")"+M+"*"),U=new RegExp(M+"|>"),X=new RegExp(F),V=new RegExp("^"+I+"$"),G={ID:new RegExp("^#("+I+")"),CLASS:new RegExp("^\\.("+I+")"),TAG:new RegExp("^("+I+"|[*])"),ATTR:new RegExp("^"+W),PSEUDO:new RegExp("^"+F),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+M+"*(even|odd|(([+-]|)(\\d*)n|)"+M+"*(?:([+-]|)"+M+"*(\\d+)|))"+M+"*\\)|)","i"),bool:new RegExp("^(?:"+R+")$","i"),needsContext:new RegExp("^"+M+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+M+"*((?:-\\d)?\\d*)"+M+"*\\)|)(?=[^-]|$)","i")},Y=/HTML$/i,Q=/^(?:input|select|textarea|button)$/i,J=/^h\d$/i,K=/^[^{]+\{\s*\[native \w/,Z=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,ee=/[+~]/,te=new RegExp("\\\\[\\da-fA-F]{1,6}"+M+"?|\\\\([^\\r\\n\\f])","g"),ne=function(e,t){var n="0x"+e.slice(1)-65536;return t||(n<0?String.fromCharCode(n+65536):String.fromCharCode(n>>10|55296,1023&n|56320))},re=/([\0-\x1f\x7f]|^-?\d)|^-$|[^\0-\x1f\x7f-\uFFFF\w-]/g,ie=function(e,t){return t?"\0"===e?"\ufffd":e.slice(0,-1)+"\\"+e.charCodeAt(e.length-1).toString(16)+" ":"\\"+e},oe=function(){T()},ae=be(function(e){return!0===e.disabled&&"fieldset"===e.nodeName.toLowerCase()},{dir:"parentNode",next:"legend"});try{H.apply(t=O.call(p.childNodes),p.childNodes),t[p.childNodes.length].nodeType}catch(e){H={apply:t.length?function(e,t){L.apply(e,O.call(t))}:function(e,t){var n=e.length,r=0;while(e[n++]=t[r++]);e.length=n-1}}}function se(t,e,n,r){var i,o,a,s,u,l,c,f=e&&e.ownerDocument,p=e?e.nodeType:9;if(n=n||[],"string"!=typeof t||!t||1!==p&&9!==p&&11!==p)return n;if(!r&&(T(e),e=e||C,E)){if(11!==p&&(u=Z.exec(t)))if(i=u[1]){if(9===p){if(!(a=e.getElementById(i)))return n;if(a.id===i)return n.push(a),n}else if(f&&(a=f.getElementById(i))&&y(e,a)&&a.id===i)return n.push(a),n}else{if(u[2])return H.apply(n,e.getElementsByTagName(t)),n;if((i=u[3])&&d.getElementsByClassName&&e.getElementsByClassName)return H.apply(n,e.getElementsByClassName(i)),n}if(d.qsa&&!N[t+" "]&&(!v||!v.test(t))&&(1!==p||"object"!==e.nodeName.toLowerCase())){if(c=t,f=e,1===p&&(U.test(t)||z.test(t))){(f=ee.test(t)&&ye(e.parentNode)||e)===e&&d.scope||((s=e.getAttribute("id"))?s=s.replace(re,ie):e.setAttribute("id",s=S)),o=(l=h(t)).length;while(o--)l[o]=(s?"#"+s:":scope")+" "+xe(l[o]);c=l.join(",")}try{return H.apply(n,f.querySelectorAll(c)),n}catch(e){N(t,!0)}finally{s===S&&e.removeAttribute("id")}}}return g(t.replace($,"$1"),e,n,r)}function ue(){var r=[];return function e(t,n){return r.push(t+" ")>b.cacheLength&&delete e[r.shift()],e[t+" "]=n}}function le(e){return e[S]=!0,e}function ce(e){var t=C.createElement("fieldset");try{return!!e(t)}catch(e){return!1}finally{t.parentNode&&t.parentNode.removeChild(t),t=null}}function fe(e,t){var n=e.split("|"),r=n.length;while(r--)b.attrHandle[n[r]]=t}function pe(e,t){var n=t&&e,r=n&&1===e.nodeType&&1===t.nodeType&&e.sourceIndex-t.sourceIndex;if(r)return r;if(n)while(n=n.nextSibling)if(n===t)return-1;return e?1:-1}function de(t){return function(e){return"input"===e.nodeName.toLowerCase()&&e.type===t}}function he(n){return function(e){var t=e.nodeName.toLowerCase();return("input"===t||"button"===t)&&e.type===n}}function ge(t){return function(e){return"form"in e?e.parentNode&&!1===e.disabled?"label"in e?"label"in e.parentNode?e.parentNode.disabled===t:e.disabled===t:e.isDisabled===t||e.isDisabled!==!t&&ae(e)===t:e.disabled===t:"label"in e&&e.disabled===t}}function ve(a){return le(function(o){return o=+o,le(function(e,t){var n,r=a([],e.length,o),i=r.length;while(i--)e[n=r[i]]&&(e[n]=!(t[n]=e[n]))})})}function ye(e){return e&&"undefined"!=typeof e.getElementsByTagName&&e}for(e in d=se.support={},i=se.isXML=function(e){var t=e.namespaceURI,n=(e.ownerDocument||e).documentElement;return!Y.test(t||n&&n.nodeName||"HTML")},T=se.setDocument=function(e){var t,n,r=e?e.ownerDocument||e:p;return r!=C&&9===r.nodeType&&r.documentElement&&(a=(C=r).documentElement,E=!i(C),p!=C&&(n=C.defaultView)&&n.top!==n&&(n.addEventListener?n.addEventListener("unload",oe,!1):n.attachEvent&&n.attachEvent("onunload",oe)),d.scope=ce(function(e){return a.appendChild(e).appendChild(C.createElement("div")),"undefined"!=typeof e.querySelectorAll&&!e.querySelectorAll(":scope fieldset div").length}),d.attributes=ce(function(e){return e.className="i",!e.getAttribute("className")}),d.getElementsByTagName=ce(function(e){return e.appendChild(C.createComment("")),!e.getElementsByTagName("*").length}),d.getElementsByClassName=K.test(C.getElementsByClassName),d.getById=ce(function(e){return a.appendChild(e).id=S,!C.getElementsByName||!C.getElementsByName(S).length}),d.getById?(b.filter.ID=function(e){var t=e.replace(te,ne);return function(e){return e.getAttribute("id")===t}},b.find.ID=function(e,t){if("undefined"!=typeof t.getElementById&&E){var n=t.getElementById(e);return n?[n]:[]}}):(b.filter.ID=function(e){var n=e.replace(te,ne);return function(e){var t="undefined"!=typeof e.getAttributeNode&&e.getAttributeNode("id");return t&&t.value===n}},b.find.ID=function(e,t){if("undefined"!=typeof t.getElementById&&E){var n,r,i,o=t.getElementById(e);if(o){if((n=o.getAttributeNode("id"))&&n.value===e)return[o];i=t.getElementsByName(e),r=0;while(o=i[r++])if((n=o.getAttributeNode("id"))&&n.value===e)return[o]}return[]}}),b.find.TAG=d.getElementsByTagName?function(e,t){return"undefined"!=typeof t.getElementsByTagName?t.getElementsByTagName(e):d.qsa?t.querySelectorAll(e):void 0}:function(e,t){var n,r=[],i=0,o=t.getElementsByTagName(e);if("*"===e){while(n=o[i++])1===n.nodeType&&r.push(n);return r}return o},b.find.CLASS=d.getElementsByClassName&&function(e,t){if("undefined"!=typeof t.getElementsByClassName&&E)return t.getElementsByClassName(e)},s=[],v=[],(d.qsa=K.test(C.querySelectorAll))&&(ce(function(e){var t;a.appendChild(e).innerHTML="",e.querySelectorAll("[msallowcapture^='']").length&&v.push("[*^$]="+M+"*(?:''|\"\")"),e.querySelectorAll("[selected]").length||v.push("\\["+M+"*(?:value|"+R+")"),e.querySelectorAll("[id~="+S+"-]").length||v.push("~="),(t=C.createElement("input")).setAttribute("name",""),e.appendChild(t),e.querySelectorAll("[name='']").length||v.push("\\["+M+"*name"+M+"*="+M+"*(?:''|\"\")"),e.querySelectorAll(":checked").length||v.push(":checked"),e.querySelectorAll("a#"+S+"+*").length||v.push(".#.+[+~]"),e.querySelectorAll("\\\f"),v.push("[\\r\\n\\f]")}),ce(function(e){e.innerHTML="";var t=C.createElement("input");t.setAttribute("type","hidden"),e.appendChild(t).setAttribute("name","D"),e.querySelectorAll("[name=d]").length&&v.push("name"+M+"*[*^$|!~]?="),2!==e.querySelectorAll(":enabled").length&&v.push(":enabled",":disabled"),a.appendChild(e).disabled=!0,2!==e.querySelectorAll(":disabled").length&&v.push(":enabled",":disabled"),e.querySelectorAll("*,:x"),v.push(",.*:")})),(d.matchesSelector=K.test(c=a.matches||a.webkitMatchesSelector||a.mozMatchesSelector||a.oMatchesSelector||a.msMatchesSelector))&&ce(function(e){d.disconnectedMatch=c.call(e,"*"),c.call(e,"[s!='']:x"),s.push("!=",F)}),v=v.length&&new RegExp(v.join("|")),s=s.length&&new RegExp(s.join("|")),t=K.test(a.compareDocumentPosition),y=t||K.test(a.contains)?function(e,t){var n=9===e.nodeType?e.documentElement:e,r=t&&t.parentNode;return e===r||!(!r||1!==r.nodeType||!(n.contains?n.contains(r):e.compareDocumentPosition&&16&e.compareDocumentPosition(r)))}:function(e,t){if(t)while(t=t.parentNode)if(t===e)return!0;return!1},D=t?function(e,t){if(e===t)return l=!0,0;var n=!e.compareDocumentPosition-!t.compareDocumentPosition;return n||(1&(n=(e.ownerDocument||e)==(t.ownerDocument||t)?e.compareDocumentPosition(t):1)||!d.sortDetached&&t.compareDocumentPosition(e)===n?e==C||e.ownerDocument==p&&y(p,e)?-1:t==C||t.ownerDocument==p&&y(p,t)?1:u?P(u,e)-P(u,t):0:4&n?-1:1)}:function(e,t){if(e===t)return l=!0,0;var n,r=0,i=e.parentNode,o=t.parentNode,a=[e],s=[t];if(!i||!o)return e==C?-1:t==C?1:i?-1:o?1:u?P(u,e)-P(u,t):0;if(i===o)return pe(e,t);n=e;while(n=n.parentNode)a.unshift(n);n=t;while(n=n.parentNode)s.unshift(n);while(a[r]===s[r])r++;return r?pe(a[r],s[r]):a[r]==p?-1:s[r]==p?1:0}),C},se.matches=function(e,t){return se(e,null,null,t)},se.matchesSelector=function(e,t){if(T(e),d.matchesSelector&&E&&!N[t+" "]&&(!s||!s.test(t))&&(!v||!v.test(t)))try{var n=c.call(e,t);if(n||d.disconnectedMatch||e.document&&11!==e.document.nodeType)return n}catch(e){N(t,!0)}return 0":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(e){return e[1]=e[1].replace(te,ne),e[3]=(e[3]||e[4]||e[5]||"").replace(te,ne),"~="===e[2]&&(e[3]=" "+e[3]+" "),e.slice(0,4)},CHILD:function(e){return e[1]=e[1].toLowerCase(),"nth"===e[1].slice(0,3)?(e[3]||se.error(e[0]),e[4]=+(e[4]?e[5]+(e[6]||1):2*("even"===e[3]||"odd"===e[3])),e[5]=+(e[7]+e[8]||"odd"===e[3])):e[3]&&se.error(e[0]),e},PSEUDO:function(e){var t,n=!e[6]&&e[2];return G.CHILD.test(e[0])?null:(e[3]?e[2]=e[4]||e[5]||"":n&&X.test(n)&&(t=h(n,!0))&&(t=n.indexOf(")",n.length-t)-n.length)&&(e[0]=e[0].slice(0,t),e[2]=n.slice(0,t)),e.slice(0,3))}},filter:{TAG:function(e){var t=e.replace(te,ne).toLowerCase();return"*"===e?function(){return!0}:function(e){return e.nodeName&&e.nodeName.toLowerCase()===t}},CLASS:function(e){var t=m[e+" "];return t||(t=new RegExp("(^|"+M+")"+e+"("+M+"|$)"))&&m(e,function(e){return t.test("string"==typeof e.className&&e.className||"undefined"!=typeof e.getAttribute&&e.getAttribute("class")||"")})},ATTR:function(n,r,i){return function(e){var t=se.attr(e,n);return null==t?"!="===r:!r||(t+="","="===r?t===i:"!="===r?t!==i:"^="===r?i&&0===t.indexOf(i):"*="===r?i&&-1:\x20\t\r\n\f]*)[\x20\t\r\n\f]*\/?>(?:<\/\1>|)$/i;function D(e,n,r){return m(n)?S.grep(e,function(e,t){return!!n.call(e,t,e)!==r}):n.nodeType?S.grep(e,function(e){return e===n!==r}):"string"!=typeof n?S.grep(e,function(e){return-1)[^>]*|#([\w-]+))$/;(S.fn.init=function(e,t,n){var r,i;if(!e)return this;if(n=n||j,"string"==typeof e){if(!(r="<"===e[0]&&">"===e[e.length-1]&&3<=e.length?[null,e,null]:q.exec(e))||!r[1]&&t)return!t||t.jquery?(t||n).find(e):this.constructor(t).find(e);if(r[1]){if(t=t instanceof S?t[0]:t,S.merge(this,S.parseHTML(r[1],t&&t.nodeType?t.ownerDocument||t:E,!0)),N.test(r[1])&&S.isPlainObject(t))for(r in t)m(this[r])?this[r](t[r]):this.attr(r,t[r]);return this}return(i=E.getElementById(r[2]))&&(this[0]=i,this.length=1),this}return e.nodeType?(this[0]=e,this.length=1,this):m(e)?void 0!==n.ready?n.ready(e):e(S):S.makeArray(e,this)}).prototype=S.fn,j=S(E);var L=/^(?:parents|prev(?:Until|All))/,H={children:!0,contents:!0,next:!0,prev:!0};function O(e,t){while((e=e[t])&&1!==e.nodeType);return e}S.fn.extend({has:function(e){var t=S(e,this),n=t.length;return this.filter(function(){for(var e=0;e\x20\t\r\n\f]*)/i,he=/^$|^module$|\/(?:java|ecma)script/i;ce=E.createDocumentFragment().appendChild(E.createElement("div")),(fe=E.createElement("input")).setAttribute("type","radio"),fe.setAttribute("checked","checked"),fe.setAttribute("name","t"),ce.appendChild(fe),y.checkClone=ce.cloneNode(!0).cloneNode(!0).lastChild.checked,ce.innerHTML="",y.noCloneChecked=!!ce.cloneNode(!0).lastChild.defaultValue,ce.innerHTML="",y.option=!!ce.lastChild;var ge={thead:[1,"","
      "],col:[2,"","
      "],tr:[2,"","
      "],td:[3,"","
      "],_default:[0,"",""]};function ve(e,t){var n;return n="undefined"!=typeof e.getElementsByTagName?e.getElementsByTagName(t||"*"):"undefined"!=typeof e.querySelectorAll?e.querySelectorAll(t||"*"):[],void 0===t||t&&A(e,t)?S.merge([e],n):n}function ye(e,t){for(var n=0,r=e.length;n",""]);var me=/<|&#?\w+;/;function xe(e,t,n,r,i){for(var o,a,s,u,l,c,f=t.createDocumentFragment(),p=[],d=0,h=e.length;d\s*$/g;function qe(e,t){return A(e,"table")&&A(11!==t.nodeType?t:t.firstChild,"tr")&&S(e).children("tbody")[0]||e}function Le(e){return e.type=(null!==e.getAttribute("type"))+"/"+e.type,e}function He(e){return"true/"===(e.type||"").slice(0,5)?e.type=e.type.slice(5):e.removeAttribute("type"),e}function Oe(e,t){var n,r,i,o,a,s;if(1===t.nodeType){if(Y.hasData(e)&&(s=Y.get(e).events))for(i in Y.remove(t,"handle events"),s)for(n=0,r=s[i].length;n").attr(n.scriptAttrs||{}).prop({charset:n.scriptCharset,src:n.url}).on("load error",i=function(e){r.remove(),i=null,e&&t("error"===e.type?404:200,e.type)}),E.head.appendChild(r[0])},abort:function(){i&&i()}}});var Ut,Xt=[],Vt=/(=)\?(?=&|$)|\?\?/;S.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var e=Xt.pop()||S.expando+"_"+Ct.guid++;return this[e]=!0,e}}),S.ajaxPrefilter("json jsonp",function(e,t,n){var r,i,o,a=!1!==e.jsonp&&(Vt.test(e.url)?"url":"string"==typeof e.data&&0===(e.contentType||"").indexOf("application/x-www-form-urlencoded")&&Vt.test(e.data)&&"data");if(a||"jsonp"===e.dataTypes[0])return r=e.jsonpCallback=m(e.jsonpCallback)?e.jsonpCallback():e.jsonpCallback,a?e[a]=e[a].replace(Vt,"$1"+r):!1!==e.jsonp&&(e.url+=(Et.test(e.url)?"&":"?")+e.jsonp+"="+r),e.converters["script json"]=function(){return o||S.error(r+" was not called"),o[0]},e.dataTypes[0]="json",i=C[r],C[r]=function(){o=arguments},n.always(function(){void 0===i?S(C).removeProp(r):C[r]=i,e[r]&&(e.jsonpCallback=t.jsonpCallback,Xt.push(r)),o&&m(i)&&i(o[0]),o=i=void 0}),"script"}),y.createHTMLDocument=((Ut=E.implementation.createHTMLDocument("").body).innerHTML="
      ",2===Ut.childNodes.length),S.parseHTML=function(e,t,n){return"string"!=typeof e?[]:("boolean"==typeof t&&(n=t,t=!1),t||(y.createHTMLDocument?((r=(t=E.implementation.createHTMLDocument("")).createElement("base")).href=E.location.href,t.head.appendChild(r)):t=E),o=!n&&[],(i=N.exec(e))?[t.createElement(i[1])]:(i=xe([e],t,o),o&&o.length&&S(o).remove(),S.merge([],i.childNodes)));var r,i,o},S.fn.load=function(e,t,n){var r,i,o,a=this,s=e.indexOf(" ");return-1").append(S.parseHTML(e)).find(r):e)}).always(n&&function(e,t){a.each(function(){n.apply(this,o||[e.responseText,t,e])})}),this},S.expr.pseudos.animated=function(t){return S.grep(S.timers,function(e){return t===e.elem}).length},S.offset={setOffset:function(e,t,n){var r,i,o,a,s,u,l=S.css(e,"position"),c=S(e),f={};"static"===l&&(e.style.position="relative"),s=c.offset(),o=S.css(e,"top"),u=S.css(e,"left"),("absolute"===l||"fixed"===l)&&-1<(o+u).indexOf("auto")?(a=(r=c.position()).top,i=r.left):(a=parseFloat(o)||0,i=parseFloat(u)||0),m(t)&&(t=t.call(e,n,S.extend({},s))),null!=t.top&&(f.top=t.top-s.top+a),null!=t.left&&(f.left=t.left-s.left+i),"using"in t?t.using.call(e,f):("number"==typeof f.top&&(f.top+="px"),"number"==typeof f.left&&(f.left+="px"),c.css(f))}},S.fn.extend({offset:function(t){if(arguments.length)return void 0===t?this:this.each(function(e){S.offset.setOffset(this,t,e)});var e,n,r=this[0];return r?r.getClientRects().length?(e=r.getBoundingClientRect(),n=r.ownerDocument.defaultView,{top:e.top+n.pageYOffset,left:e.left+n.pageXOffset}):{top:0,left:0}:void 0},position:function(){if(this[0]){var e,t,n,r=this[0],i={top:0,left:0};if("fixed"===S.css(r,"position"))t=r.getBoundingClientRect();else{t=this.offset(),n=r.ownerDocument,e=r.offsetParent||n.documentElement;while(e&&(e===n.body||e===n.documentElement)&&"static"===S.css(e,"position"))e=e.parentNode;e&&e!==r&&1===e.nodeType&&((i=S(e).offset()).top+=S.css(e,"borderTopWidth",!0),i.left+=S.css(e,"borderLeftWidth",!0))}return{top:t.top-i.top-S.css(r,"marginTop",!0),left:t.left-i.left-S.css(r,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){var e=this.offsetParent;while(e&&"static"===S.css(e,"position"))e=e.offsetParent;return e||re})}}),S.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(t,i){var o="pageYOffset"===i;S.fn[t]=function(e){return $(this,function(e,t,n){var r;if(x(e)?r=e:9===e.nodeType&&(r=e.defaultView),void 0===n)return r?r[i]:e[t];r?r.scrollTo(o?r.pageXOffset:n,o?n:r.pageYOffset):e[t]=n},t,e,arguments.length)}}),S.each(["top","left"],function(e,n){S.cssHooks[n]=$e(y.pixelPosition,function(e,t){if(t)return t=Be(e,n),Me.test(t)?S(e).position()[n]+"px":t})}),S.each({Height:"height",Width:"width"},function(a,s){S.each({padding:"inner"+a,content:s,"":"outer"+a},function(r,o){S.fn[o]=function(e,t){var n=arguments.length&&(r||"boolean"!=typeof e),i=r||(!0===e||!0===t?"margin":"border");return $(this,function(e,t,n){var r;return x(e)?0===o.indexOf("outer")?e["inner"+a]:e.document.documentElement["client"+a]:9===e.nodeType?(r=e.documentElement,Math.max(e.body["scroll"+a],r["scroll"+a],e.body["offset"+a],r["offset"+a],r["client"+a])):void 0===n?S.css(e,t,i):S.style(e,t,n,i)},s,n?e:void 0,n)}})}),S.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(e,t){S.fn[t]=function(e){return this.on(t,e)}}),S.fn.extend({bind:function(e,t,n){return this.on(e,null,t,n)},unbind:function(e,t){return this.off(e,null,t)},delegate:function(e,t,n,r){return this.on(t,e,n,r)},undelegate:function(e,t,n){return 1===arguments.length?this.off(e,"**"):this.off(t,e||"**",n)},hover:function(e,t){return this.mouseenter(e).mouseleave(t||e)}}),S.each("blur focus focusin focusout resize scroll click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup contextmenu".split(" "),function(e,n){S.fn[n]=function(e,t){return 0+~]|"+ge+")"+ge+"*"),x=new RegExp(ge+"|>"),j=new RegExp(g),A=new RegExp("^"+t+"$"),D={ID:new RegExp("^#("+t+")"),CLASS:new RegExp("^\\.("+t+")"),TAG:new RegExp("^("+t+"|[*])"),ATTR:new RegExp("^"+p),PSEUDO:new RegExp("^"+g),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+ge+"*(even|odd|(([+-]|)(\\d*)n|)"+ge+"*(?:([+-]|)"+ge+"*(\\d+)|))"+ge+"*\\)|)","i"),bool:new RegExp("^(?:"+f+")$","i"),needsContext:new RegExp("^"+ge+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+ge+"*((?:-\\d)?\\d*)"+ge+"*\\)|)(?=[^-]|$)","i")},N=/^(?:input|select|textarea|button)$/i,q=/^h\d$/i,L=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,H=/[+~]/,O=new RegExp("\\\\[\\da-fA-F]{1,6}"+ge+"?|\\\\([^\\r\\n\\f])","g"),P=function(e,t){var n="0x"+e.slice(1)-65536;return t||(n<0?String.fromCharCode(n+65536):String.fromCharCode(n>>10|55296,1023&n|56320))},M=function(){V()},R=J(function(e){return!0===e.disabled&&fe(e,"fieldset")},{dir:"parentNode",next:"legend"});try{k.apply(oe=ae.call(ye.childNodes),ye.childNodes),oe[ye.childNodes.length].nodeType}catch(e){k={apply:function(e,t){me.apply(e,ae.call(t))},call:function(e){me.apply(e,ae.call(arguments,1))}}}function I(t,e,n,r){var i,o,a,s,u,l,c,f=e&&e.ownerDocument,p=e?e.nodeType:9;if(n=n||[],"string"!=typeof t||!t||1!==p&&9!==p&&11!==p)return n;if(!r&&(V(e),e=e||T,C)){if(11!==p&&(u=L.exec(t)))if(i=u[1]){if(9===p){if(!(a=e.getElementById(i)))return n;if(a.id===i)return k.call(n,a),n}else if(f&&(a=f.getElementById(i))&&I.contains(e,a)&&a.id===i)return k.call(n,a),n}else{if(u[2])return k.apply(n,e.getElementsByTagName(t)),n;if((i=u[3])&&e.getElementsByClassName)return k.apply(n,e.getElementsByClassName(i)),n}if(!(h[t+" "]||d&&d.test(t))){if(c=t,f=e,1===p&&(x.test(t)||m.test(t))){(f=H.test(t)&&U(e.parentNode)||e)==e&&le.scope||((s=e.getAttribute("id"))?s=ce.escapeSelector(s):e.setAttribute("id",s=S)),o=(l=Y(t)).length;while(o--)l[o]=(s?"#"+s:":scope")+" "+Q(l[o]);c=l.join(",")}try{return k.apply(n,f.querySelectorAll(c)),n}catch(e){h(t,!0)}finally{s===S&&e.removeAttribute("id")}}}return re(t.replace(ve,"$1"),e,n,r)}function W(){var r=[];return function e(t,n){return r.push(t+" ")>b.cacheLength&&delete e[r.shift()],e[t+" "]=n}}function F(e){return e[S]=!0,e}function $(e){var t=T.createElement("fieldset");try{return!!e(t)}catch(e){return!1}finally{t.parentNode&&t.parentNode.removeChild(t),t=null}}function B(t){return function(e){return fe(e,"input")&&e.type===t}}function _(t){return function(e){return(fe(e,"input")||fe(e,"button"))&&e.type===t}}function z(t){return function(e){return"form"in e?e.parentNode&&!1===e.disabled?"label"in e?"label"in e.parentNode?e.parentNode.disabled===t:e.disabled===t:e.isDisabled===t||e.isDisabled!==!t&&R(e)===t:e.disabled===t:"label"in e&&e.disabled===t}}function X(a){return F(function(o){return o=+o,F(function(e,t){var n,r=a([],e.length,o),i=r.length;while(i--)e[n=r[i]]&&(e[n]=!(t[n]=e[n]))})})}function U(e){return e&&"undefined"!=typeof e.getElementsByTagName&&e}function V(e){var t,n=e?e.ownerDocument||e:ye;return n!=T&&9===n.nodeType&&n.documentElement&&(r=(T=n).documentElement,C=!ce.isXMLDoc(T),i=r.matches||r.webkitMatchesSelector||r.msMatchesSelector,r.msMatchesSelector&&ye!=T&&(t=T.defaultView)&&t.top!==t&&t.addEventListener("unload",M),le.getById=$(function(e){return r.appendChild(e).id=ce.expando,!T.getElementsByName||!T.getElementsByName(ce.expando).length}),le.disconnectedMatch=$(function(e){return i.call(e,"*")}),le.scope=$(function(){return T.querySelectorAll(":scope")}),le.cssHas=$(function(){try{return T.querySelector(":has(*,:jqfake)"),!1}catch(e){return!0}}),le.getById?(b.filter.ID=function(e){var t=e.replace(O,P);return function(e){return e.getAttribute("id")===t}},b.find.ID=function(e,t){if("undefined"!=typeof t.getElementById&&C){var n=t.getElementById(e);return n?[n]:[]}}):(b.filter.ID=function(e){var n=e.replace(O,P);return function(e){var t="undefined"!=typeof e.getAttributeNode&&e.getAttributeNode("id");return t&&t.value===n}},b.find.ID=function(e,t){if("undefined"!=typeof t.getElementById&&C){var n,r,i,o=t.getElementById(e);if(o){if((n=o.getAttributeNode("id"))&&n.value===e)return[o];i=t.getElementsByName(e),r=0;while(o=i[r++])if((n=o.getAttributeNode("id"))&&n.value===e)return[o]}return[]}}),b.find.TAG=function(e,t){return"undefined"!=typeof t.getElementsByTagName?t.getElementsByTagName(e):t.querySelectorAll(e)},b.find.CLASS=function(e,t){if("undefined"!=typeof t.getElementsByClassName&&C)return t.getElementsByClassName(e)},d=[],$(function(e){var t;r.appendChild(e).innerHTML="",e.querySelectorAll("[selected]").length||d.push("\\["+ge+"*(?:value|"+f+")"),e.querySelectorAll("[id~="+S+"-]").length||d.push("~="),e.querySelectorAll("a#"+S+"+*").length||d.push(".#.+[+~]"),e.querySelectorAll(":checked").length||d.push(":checked"),(t=T.createElement("input")).setAttribute("type","hidden"),e.appendChild(t).setAttribute("name","D"),r.appendChild(e).disabled=!0,2!==e.querySelectorAll(":disabled").length&&d.push(":enabled",":disabled"),(t=T.createElement("input")).setAttribute("name",""),e.appendChild(t),e.querySelectorAll("[name='']").length||d.push("\\["+ge+"*name"+ge+"*="+ge+"*(?:''|\"\")")}),le.cssHas||d.push(":has"),d=d.length&&new RegExp(d.join("|")),l=function(e,t){if(e===t)return a=!0,0;var n=!e.compareDocumentPosition-!t.compareDocumentPosition;return n||(1&(n=(e.ownerDocument||e)==(t.ownerDocument||t)?e.compareDocumentPosition(t):1)||!le.sortDetached&&t.compareDocumentPosition(e)===n?e===T||e.ownerDocument==ye&&I.contains(ye,e)?-1:t===T||t.ownerDocument==ye&&I.contains(ye,t)?1:o?se.call(o,e)-se.call(o,t):0:4&n?-1:1)}),T}for(e in I.matches=function(e,t){return I(e,null,null,t)},I.matchesSelector=function(e,t){if(V(e),C&&!h[t+" "]&&(!d||!d.test(t)))try{var n=i.call(e,t);if(n||le.disconnectedMatch||e.document&&11!==e.document.nodeType)return n}catch(e){h(t,!0)}return 0":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(e){return e[1]=e[1].replace(O,P),e[3]=(e[3]||e[4]||e[5]||"").replace(O,P),"~="===e[2]&&(e[3]=" "+e[3]+" "),e.slice(0,4)},CHILD:function(e){return e[1]=e[1].toLowerCase(),"nth"===e[1].slice(0,3)?(e[3]||I.error(e[0]),e[4]=+(e[4]?e[5]+(e[6]||1):2*("even"===e[3]||"odd"===e[3])),e[5]=+(e[7]+e[8]||"odd"===e[3])):e[3]&&I.error(e[0]),e},PSEUDO:function(e){var t,n=!e[6]&&e[2];return D.CHILD.test(e[0])?null:(e[3]?e[2]=e[4]||e[5]||"":n&&j.test(n)&&(t=Y(n,!0))&&(t=n.indexOf(")",n.length-t)-n.length)&&(e[0]=e[0].slice(0,t),e[2]=n.slice(0,t)),e.slice(0,3))}},filter:{TAG:function(e){var t=e.replace(O,P).toLowerCase();return"*"===e?function(){return!0}:function(e){return fe(e,t)}},CLASS:function(e){var t=s[e+" "];return t||(t=new RegExp("(^|"+ge+")"+e+"("+ge+"|$)"))&&s(e,function(e){return t.test("string"==typeof e.className&&e.className||"undefined"!=typeof e.getAttribute&&e.getAttribute("class")||"")})},ATTR:function(n,r,i){return function(e){var t=I.attr(e,n);return null==t?"!="===r:!r||(t+="","="===r?t===i:"!="===r?t!==i:"^="===r?i&&0===t.indexOf(i):"*="===r?i&&-1:\x20\t\r\n\f]*)[\x20\t\r\n\f]*\/?>(?:<\/\1>|)$/i;function T(e,n,r){return v(n)?ce.grep(e,function(e,t){return!!n.call(e,t,e)!==r}):n.nodeType?ce.grep(e,function(e){return e===n!==r}):"string"!=typeof n?ce.grep(e,function(e){return-1)[^>]*|#([\w-]+))$/;(ce.fn.init=function(e,t,n){var r,i;if(!e)return this;if(n=n||k,"string"==typeof e){if(!(r="<"===e[0]&&">"===e[e.length-1]&&3<=e.length?[null,e,null]:S.exec(e))||!r[1]&&t)return!t||t.jquery?(t||n).find(e):this.constructor(t).find(e);if(r[1]){if(t=t instanceof ce?t[0]:t,ce.merge(this,ce.parseHTML(r[1],t&&t.nodeType?t.ownerDocument||t:C,!0)),w.test(r[1])&&ce.isPlainObject(t))for(r in t)v(this[r])?this[r](t[r]):this.attr(r,t[r]);return this}return(i=C.getElementById(r[2]))&&(this[0]=i,this.length=1),this}return e.nodeType?(this[0]=e,this.length=1,this):v(e)?void 0!==n.ready?n.ready(e):e(ce):ce.makeArray(e,this)}).prototype=ce.fn,k=ce(C);var E=/^(?:parents|prev(?:Until|All))/,j={children:!0,contents:!0,next:!0,prev:!0};function A(e,t){while((e=e[t])&&1!==e.nodeType);return e}ce.fn.extend({has:function(e){var t=ce(e,this),n=t.length;return this.filter(function(){for(var e=0;e\x20\t\r\n\f]*)/i,Ce=/^$|^module$|\/(?:java|ecma)script/i;xe=C.createDocumentFragment().appendChild(C.createElement("div")),(be=C.createElement("input")).setAttribute("type","radio"),be.setAttribute("checked","checked"),be.setAttribute("name","t"),xe.appendChild(be),le.checkClone=xe.cloneNode(!0).cloneNode(!0).lastChild.checked,xe.innerHTML="",le.noCloneChecked=!!xe.cloneNode(!0).lastChild.defaultValue,xe.innerHTML="",le.option=!!xe.lastChild;var ke={thead:[1,"","
      "],col:[2,"","
      "],tr:[2,"","
      "],td:[3,"","
      "],_default:[0,"",""]};function Se(e,t){var n;return n="undefined"!=typeof e.getElementsByTagName?e.getElementsByTagName(t||"*"):"undefined"!=typeof e.querySelectorAll?e.querySelectorAll(t||"*"):[],void 0===t||t&&fe(e,t)?ce.merge([e],n):n}function Ee(e,t){for(var n=0,r=e.length;n",""]);var je=/<|&#?\w+;/;function Ae(e,t,n,r,i){for(var o,a,s,u,l,c,f=t.createDocumentFragment(),p=[],d=0,h=e.length;d\s*$/g;function Re(e,t){return fe(e,"table")&&fe(11!==t.nodeType?t:t.firstChild,"tr")&&ce(e).children("tbody")[0]||e}function Ie(e){return e.type=(null!==e.getAttribute("type"))+"/"+e.type,e}function We(e){return"true/"===(e.type||"").slice(0,5)?e.type=e.type.slice(5):e.removeAttribute("type"),e}function Fe(e,t){var n,r,i,o,a,s;if(1===t.nodeType){if(_.hasData(e)&&(s=_.get(e).events))for(i in _.remove(t,"handle events"),s)for(n=0,r=s[i].length;n").attr(n.scriptAttrs||{}).prop({charset:n.scriptCharset,src:n.url}).on("load error",i=function(e){r.remove(),i=null,e&&t("error"===e.type?404:200,e.type)}),C.head.appendChild(r[0])},abort:function(){i&&i()}}});var Jt,Kt=[],Zt=/(=)\?(?=&|$)|\?\?/;ce.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var e=Kt.pop()||ce.expando+"_"+jt.guid++;return this[e]=!0,e}}),ce.ajaxPrefilter("json jsonp",function(e,t,n){var r,i,o,a=!1!==e.jsonp&&(Zt.test(e.url)?"url":"string"==typeof e.data&&0===(e.contentType||"").indexOf("application/x-www-form-urlencoded")&&Zt.test(e.data)&&"data");if(a||"jsonp"===e.dataTypes[0])return r=e.jsonpCallback=v(e.jsonpCallback)?e.jsonpCallback():e.jsonpCallback,a?e[a]=e[a].replace(Zt,"$1"+r):!1!==e.jsonp&&(e.url+=(At.test(e.url)?"&":"?")+e.jsonp+"="+r),e.converters["script json"]=function(){return o||ce.error(r+" was not called"),o[0]},e.dataTypes[0]="json",i=ie[r],ie[r]=function(){o=arguments},n.always(function(){void 0===i?ce(ie).removeProp(r):ie[r]=i,e[r]&&(e.jsonpCallback=t.jsonpCallback,Kt.push(r)),o&&v(i)&&i(o[0]),o=i=void 0}),"script"}),le.createHTMLDocument=((Jt=C.implementation.createHTMLDocument("").body).innerHTML="
      ",2===Jt.childNodes.length),ce.parseHTML=function(e,t,n){return"string"!=typeof e?[]:("boolean"==typeof t&&(n=t,t=!1),t||(le.createHTMLDocument?((r=(t=C.implementation.createHTMLDocument("")).createElement("base")).href=C.location.href,t.head.appendChild(r)):t=C),o=!n&&[],(i=w.exec(e))?[t.createElement(i[1])]:(i=Ae([e],t,o),o&&o.length&&ce(o).remove(),ce.merge([],i.childNodes)));var r,i,o},ce.fn.load=function(e,t,n){var r,i,o,a=this,s=e.indexOf(" ");return-1").append(ce.parseHTML(e)).find(r):e)}).always(n&&function(e,t){a.each(function(){n.apply(this,o||[e.responseText,t,e])})}),this},ce.expr.pseudos.animated=function(t){return ce.grep(ce.timers,function(e){return t===e.elem}).length},ce.offset={setOffset:function(e,t,n){var r,i,o,a,s,u,l=ce.css(e,"position"),c=ce(e),f={};"static"===l&&(e.style.position="relative"),s=c.offset(),o=ce.css(e,"top"),u=ce.css(e,"left"),("absolute"===l||"fixed"===l)&&-1<(o+u).indexOf("auto")?(a=(r=c.position()).top,i=r.left):(a=parseFloat(o)||0,i=parseFloat(u)||0),v(t)&&(t=t.call(e,n,ce.extend({},s))),null!=t.top&&(f.top=t.top-s.top+a),null!=t.left&&(f.left=t.left-s.left+i),"using"in t?t.using.call(e,f):c.css(f)}},ce.fn.extend({offset:function(t){if(arguments.length)return void 0===t?this:this.each(function(e){ce.offset.setOffset(this,t,e)});var e,n,r=this[0];return r?r.getClientRects().length?(e=r.getBoundingClientRect(),n=r.ownerDocument.defaultView,{top:e.top+n.pageYOffset,left:e.left+n.pageXOffset}):{top:0,left:0}:void 0},position:function(){if(this[0]){var e,t,n,r=this[0],i={top:0,left:0};if("fixed"===ce.css(r,"position"))t=r.getBoundingClientRect();else{t=this.offset(),n=r.ownerDocument,e=r.offsetParent||n.documentElement;while(e&&(e===n.body||e===n.documentElement)&&"static"===ce.css(e,"position"))e=e.parentNode;e&&e!==r&&1===e.nodeType&&((i=ce(e).offset()).top+=ce.css(e,"borderTopWidth",!0),i.left+=ce.css(e,"borderLeftWidth",!0))}return{top:t.top-i.top-ce.css(r,"marginTop",!0),left:t.left-i.left-ce.css(r,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){var e=this.offsetParent;while(e&&"static"===ce.css(e,"position"))e=e.offsetParent;return e||J})}}),ce.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(t,i){var o="pageYOffset"===i;ce.fn[t]=function(e){return M(this,function(e,t,n){var r;if(y(e)?r=e:9===e.nodeType&&(r=e.defaultView),void 0===n)return r?r[i]:e[t];r?r.scrollTo(o?r.pageXOffset:n,o?n:r.pageYOffset):e[t]=n},t,e,arguments.length)}}),ce.each(["top","left"],function(e,n){ce.cssHooks[n]=Ye(le.pixelPosition,function(e,t){if(t)return t=Ge(e,n),_e.test(t)?ce(e).position()[n]+"px":t})}),ce.each({Height:"height",Width:"width"},function(a,s){ce.each({padding:"inner"+a,content:s,"":"outer"+a},function(r,o){ce.fn[o]=function(e,t){var n=arguments.length&&(r||"boolean"!=typeof e),i=r||(!0===e||!0===t?"margin":"border");return M(this,function(e,t,n){var r;return y(e)?0===o.indexOf("outer")?e["inner"+a]:e.document.documentElement["client"+a]:9===e.nodeType?(r=e.documentElement,Math.max(e.body["scroll"+a],r["scroll"+a],e.body["offset"+a],r["offset"+a],r["client"+a])):void 0===n?ce.css(e,t,i):ce.style(e,t,n,i)},s,n?e:void 0,n)}})}),ce.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(e,t){ce.fn[t]=function(e){return this.on(t,e)}}),ce.fn.extend({bind:function(e,t,n){return this.on(e,null,t,n)},unbind:function(e,t){return this.off(e,null,t)},delegate:function(e,t,n,r){return this.on(t,e,n,r)},undelegate:function(e,t,n){return 1===arguments.length?this.off(e,"**"):this.off(t,e||"**",n)},hover:function(e,t){return this.on("mouseenter",e).on("mouseleave",t||e)}}),ce.each("blur focus focusin focusout resize scroll click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup contextmenu".split(" "),function(e,n){ce.fn[n]=function(e,t){return 0 li.actionMenuMove > ul { } div.actionMenu ul.dnn_mact > li.actionMenuMove > ul li { padding: 8px 0 5px 10px; - height: 20px; margin: 0; border-bottom: 1px solid #cccccc; border-top: none; cursor: pointer; font-size: 12px; - font-family: Arial; line-height: 18px; text-shadow: none; } diff --git a/DNN Platform/Website/admin/Skins/LeftMenu.ascx.cs b/DNN Platform/Website/admin/Skins/LeftMenu.ascx.cs index 804a87c4dc8..062a42ca8c2 100644 --- a/DNN Platform/Website/admin/Skins/LeftMenu.ascx.cs +++ b/DNN Platform/Website/admin/Skins/LeftMenu.ascx.cs @@ -3,10 +3,10 @@ // See the LICENSE file in the project root for more information namespace DotNetNuke.UI.Skins.Controls { - using System; + using DotNetNuke.Internal.SourceGenerators; /// - [Obsolete("This skin object has been expired, create empty object to compact old skin. please ask skin vendor to update the skin if it referenced to this control.. Scheduled removal in v10.0.0.")] + [DnnDeprecated(8, 0, 0, "This skin object has been expired, create empty object to compact old skin. please ask skin vendor to update the skin if it referenced to this control")] public partial class LeftMenu : SkinObjectBase { } diff --git a/DNN Platform/Website/admin/Skins/Nav.ascx.cs b/DNN Platform/Website/admin/Skins/Nav.ascx.cs index ae8e7ed82ba..1c623b3b37b 100644 --- a/DNN Platform/Website/admin/Skins/Nav.ascx.cs +++ b/DNN Platform/Website/admin/Skins/Nav.ascx.cs @@ -1,210 +1,211 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information -namespace DotNetNuke.UI.Skins.Controls -{ - using System; +namespace DotNetNuke.UI.Skins.Controls +{ + using System; - using DotNetNuke.Common; - using DotNetNuke.Modules.NavigationProvider; - using DotNetNuke.Services.Exceptions; + using DotNetNuke.Common; + using DotNetNuke.Internal.SourceGenerators; + using DotNetNuke.Modules.NavigationProvider; + using DotNetNuke.Services.Exceptions; using DotNetNuke.UI.WebControls; - [Obsolete("Support was removed for SolPart & Similar Modules in DNN 8.x, this control is no-longer functional to that point. Usage of DDRMenu is suggested. Scheduled removal in v10.0.0.")] - public partial class Nav : NavObjectBase + [DnnDeprecated(8, 0, 0, "Support was removed for SolPart & Similar Modules in DNN 8.x, this control is no-longer functional to that point. Usage of DDRMenu is suggested.")] + public partial class Nav : NavObjectBase { /// - protected override void OnLoad(EventArgs e) - { - base.OnLoad(e); - try - { - bool blnIndicateChildren = bool.Parse(this.GetValue(this.IndicateChildren, "True")); - string strRightArrow; - string strDownArrow; - var objSkins = new SkinController(); - - // image for right facing arrow - if (!string.IsNullOrEmpty(this.IndicateChildImageSub)) - { - strRightArrow = this.IndicateChildImageSub; - } - else - { - strRightArrow = "breadcrumb.gif"; // removed APPIMAGEPATH token - https://www.dnnsoftware.com/Community/ForumsDotNetNuke/tabid/795/forumid/76/threadid/85554/scope/posts/Default.aspx - } - - // image for down facing arrow - if (!string.IsNullOrEmpty(this.IndicateChildImageRoot)) - { - strDownArrow = this.IndicateChildImageRoot; - } - else - { - strDownArrow = "menu_down.gif"; // removed APPIMAGEPATH token - https://www.dnnsoftware.com/Community/ForumsDotNetNuke/tabid/795/forumid/76/threadid/85554/scope/posts/Default.aspx - } - - // Set correct image path for all separator images - if (!string.IsNullOrEmpty(this.SeparatorHTML)) - { - this.SeparatorHTML = this.FixImagePath(this.SeparatorHTML); - } - - if (!string.IsNullOrEmpty(this.SeparatorLeftHTML)) - { - this.SeparatorLeftHTML = this.FixImagePath(this.SeparatorLeftHTML); - } - - if (!string.IsNullOrEmpty(this.SeparatorRightHTML)) - { - this.SeparatorRightHTML = this.FixImagePath(this.SeparatorRightHTML); - } - - if (!string.IsNullOrEmpty(this.SeparatorLeftHTMLBreadCrumb)) - { - this.SeparatorLeftHTMLBreadCrumb = this.FixImagePath(this.SeparatorLeftHTMLBreadCrumb); - } - - if (!string.IsNullOrEmpty(this.SeparatorRightHTMLBreadCrumb)) - { - this.SeparatorRightHTMLBreadCrumb = this.FixImagePath(this.SeparatorRightHTMLBreadCrumb); - } - - if (!string.IsNullOrEmpty(this.SeparatorLeftHTMLActive)) - { - this.SeparatorLeftHTMLActive = this.FixImagePath(this.SeparatorLeftHTMLActive); - } - - if (!string.IsNullOrEmpty(this.SeparatorRightHTMLActive)) - { - this.SeparatorRightHTMLActive = this.FixImagePath(this.SeparatorRightHTMLActive); - } - - if (!string.IsNullOrEmpty(this.NodeLeftHTMLBreadCrumbRoot)) - { - this.NodeLeftHTMLBreadCrumbRoot = this.FixImagePath(this.NodeLeftHTMLBreadCrumbRoot); - } - - if (!string.IsNullOrEmpty(this.NodeRightHTMLBreadCrumbRoot)) - { - this.NodeRightHTMLBreadCrumbRoot = this.FixImagePath(this.NodeRightHTMLBreadCrumbRoot); - } - - if (!string.IsNullOrEmpty(this.NodeLeftHTMLBreadCrumbSub)) - { - this.NodeLeftHTMLBreadCrumbSub = this.FixImagePath(this.NodeLeftHTMLBreadCrumbSub); - } - - if (!string.IsNullOrEmpty(this.NodeRightHTMLBreadCrumbSub)) - { - this.NodeRightHTMLBreadCrumbSub = this.FixImagePath(this.NodeRightHTMLBreadCrumbSub); - } - - if (!string.IsNullOrEmpty(this.NodeLeftHTMLRoot)) - { - this.NodeLeftHTMLRoot = this.FixImagePath(this.NodeLeftHTMLRoot); - } - - if (!string.IsNullOrEmpty(this.NodeRightHTMLRoot)) - { - this.NodeRightHTMLRoot = this.FixImagePath(this.NodeRightHTMLRoot); - } - - if (!string.IsNullOrEmpty(this.NodeLeftHTMLSub)) - { - this.NodeLeftHTMLSub = this.FixImagePath(this.NodeLeftHTMLSub); - } - - if (!string.IsNullOrEmpty(this.NodeRightHTMLSub)) - { - this.NodeRightHTMLSub = this.FixImagePath(this.NodeRightHTMLSub); - } - - if (string.IsNullOrEmpty(this.PathImage)) - { - this.PathImage = this.PortalSettings.HomeDirectory; - } - - if (blnIndicateChildren) - { - this.IndicateChildImageSub = strRightArrow; - if (this.ControlOrientation.ToLowerInvariant() == "vertical") - { - this.IndicateChildImageRoot = strRightArrow; - } - else - { - this.IndicateChildImageRoot = strDownArrow; - } - } - else - { - this.IndicateChildImageSub = "[APPIMAGEPATH]spacer.gif"; - } - - this.PathSystemScript = Globals.ApplicationPath + "/controls/SolpartMenu/"; - this.PathSystemImage = "[APPIMAGEPATH]"; - this.BuildNodes(null); - } - catch (Exception exc) - { - Exceptions.ProcessModuleLoadException(this, exc); - } + protected override void OnLoad(EventArgs e) + { + base.OnLoad(e); + try + { + bool blnIndicateChildren = bool.Parse(this.GetValue(this.IndicateChildren, "True")); + string strRightArrow; + string strDownArrow; + var objSkins = new SkinController(); + + // image for right facing arrow + if (!string.IsNullOrEmpty(this.IndicateChildImageSub)) + { + strRightArrow = this.IndicateChildImageSub; + } + else + { + strRightArrow = "breadcrumb.gif"; // removed APPIMAGEPATH token - https://www.dnnsoftware.com/Community/ForumsDotNetNuke/tabid/795/forumid/76/threadid/85554/scope/posts/Default.aspx + } + + // image for down facing arrow + if (!string.IsNullOrEmpty(this.IndicateChildImageRoot)) + { + strDownArrow = this.IndicateChildImageRoot; + } + else + { + strDownArrow = "menu_down.gif"; // removed APPIMAGEPATH token - https://www.dnnsoftware.com/Community/ForumsDotNetNuke/tabid/795/forumid/76/threadid/85554/scope/posts/Default.aspx + } + + // Set correct image path for all separator images + if (!string.IsNullOrEmpty(this.SeparatorHTML)) + { + this.SeparatorHTML = this.FixImagePath(this.SeparatorHTML); + } + + if (!string.IsNullOrEmpty(this.SeparatorLeftHTML)) + { + this.SeparatorLeftHTML = this.FixImagePath(this.SeparatorLeftHTML); + } + + if (!string.IsNullOrEmpty(this.SeparatorRightHTML)) + { + this.SeparatorRightHTML = this.FixImagePath(this.SeparatorRightHTML); + } + + if (!string.IsNullOrEmpty(this.SeparatorLeftHTMLBreadCrumb)) + { + this.SeparatorLeftHTMLBreadCrumb = this.FixImagePath(this.SeparatorLeftHTMLBreadCrumb); + } + + if (!string.IsNullOrEmpty(this.SeparatorRightHTMLBreadCrumb)) + { + this.SeparatorRightHTMLBreadCrumb = this.FixImagePath(this.SeparatorRightHTMLBreadCrumb); + } + + if (!string.IsNullOrEmpty(this.SeparatorLeftHTMLActive)) + { + this.SeparatorLeftHTMLActive = this.FixImagePath(this.SeparatorLeftHTMLActive); + } + + if (!string.IsNullOrEmpty(this.SeparatorRightHTMLActive)) + { + this.SeparatorRightHTMLActive = this.FixImagePath(this.SeparatorRightHTMLActive); + } + + if (!string.IsNullOrEmpty(this.NodeLeftHTMLBreadCrumbRoot)) + { + this.NodeLeftHTMLBreadCrumbRoot = this.FixImagePath(this.NodeLeftHTMLBreadCrumbRoot); + } + + if (!string.IsNullOrEmpty(this.NodeRightHTMLBreadCrumbRoot)) + { + this.NodeRightHTMLBreadCrumbRoot = this.FixImagePath(this.NodeRightHTMLBreadCrumbRoot); + } + + if (!string.IsNullOrEmpty(this.NodeLeftHTMLBreadCrumbSub)) + { + this.NodeLeftHTMLBreadCrumbSub = this.FixImagePath(this.NodeLeftHTMLBreadCrumbSub); + } + + if (!string.IsNullOrEmpty(this.NodeRightHTMLBreadCrumbSub)) + { + this.NodeRightHTMLBreadCrumbSub = this.FixImagePath(this.NodeRightHTMLBreadCrumbSub); + } + + if (!string.IsNullOrEmpty(this.NodeLeftHTMLRoot)) + { + this.NodeLeftHTMLRoot = this.FixImagePath(this.NodeLeftHTMLRoot); + } + + if (!string.IsNullOrEmpty(this.NodeRightHTMLRoot)) + { + this.NodeRightHTMLRoot = this.FixImagePath(this.NodeRightHTMLRoot); + } + + if (!string.IsNullOrEmpty(this.NodeLeftHTMLSub)) + { + this.NodeLeftHTMLSub = this.FixImagePath(this.NodeLeftHTMLSub); + } + + if (!string.IsNullOrEmpty(this.NodeRightHTMLSub)) + { + this.NodeRightHTMLSub = this.FixImagePath(this.NodeRightHTMLSub); + } + + if (string.IsNullOrEmpty(this.PathImage)) + { + this.PathImage = this.PortalSettings.HomeDirectory; + } + + if (blnIndicateChildren) + { + this.IndicateChildImageSub = strRightArrow; + if (this.ControlOrientation.ToLowerInvariant() == "vertical") + { + this.IndicateChildImageRoot = strRightArrow; + } + else + { + this.IndicateChildImageRoot = strDownArrow; + } + } + else + { + this.IndicateChildImageSub = "[APPIMAGEPATH]spacer.gif"; + } + + this.PathSystemScript = Globals.ApplicationPath + "/controls/SolpartMenu/"; + this.PathSystemImage = "[APPIMAGEPATH]"; + this.BuildNodes(null); + } + catch (Exception exc) + { + Exceptions.ProcessModuleLoadException(this, exc); + } } /// - protected override void OnInit(EventArgs e) - { - this.InitializeNavControl(this, "SolpartMenuNavigationProvider"); - this.Control.NodeClick += this.Control_NodeClick; - this.Control.PopulateOnDemand += this.Control_PopulateOnDemand; - - base.OnInit(e); - this.InitializeComponent(); - } - - private void InitializeComponent() - { - } - - private string FixImagePath(string strPath) - { - if (strPath.IndexOf("src=") != -1 && strPath.IndexOf("src=\"/") < 0) - { - return strPath.Replace("src=\"", "src=\"[SKINPATH]"); - } - else - { - return strPath; - } - } - - private void BuildNodes(DNNNode objNode) - { - DNNNodeCollection objNodes; - objNodes = this.GetNavigationNodes(objNode); - this.Control.ClearNodes(); // since we always bind we need to clear the nodes for providers that maintain their state - this.Bind(objNodes); - } - - private void Control_NodeClick(NavigationEventArgs args) - { - if (args.Node == null) - { - args.Node = Navigation.GetNavigationNode(args.ID, this.Control.ID); - } - - this.Response.Redirect(Globals.ApplicationURL(int.Parse(args.Node.Key)), true); - } - - private void Control_PopulateOnDemand(NavigationEventArgs args) - { - if (args.Node == null) - { - args.Node = Navigation.GetNavigationNode(args.ID, this.Control.ID); - } - - this.BuildNodes(args.Node); - } - } -} + protected override void OnInit(EventArgs e) + { + this.InitializeNavControl(this, "SolpartMenuNavigationProvider"); + this.Control.NodeClick += this.Control_NodeClick; + this.Control.PopulateOnDemand += this.Control_PopulateOnDemand; + + base.OnInit(e); + this.InitializeComponent(); + } + + private void InitializeComponent() + { + } + + private string FixImagePath(string strPath) + { + if (strPath.IndexOf("src=") != -1 && strPath.IndexOf("src=\"/") < 0) + { + return strPath.Replace("src=\"", "src=\"[SKINPATH]"); + } + else + { + return strPath; + } + } + + private void BuildNodes(DNNNode objNode) + { + DNNNodeCollection objNodes; + objNodes = this.GetNavigationNodes(objNode); + this.Control.ClearNodes(); // since we always bind we need to clear the nodes for providers that maintain their state + this.Bind(objNodes); + } + + private void Control_NodeClick(NavigationEventArgs args) + { + if (args.Node == null) + { + args.Node = Navigation.GetNavigationNode(args.ID, this.Control.ID); + } + + this.Response.Redirect(Globals.ApplicationURL(int.Parse(args.Node.Key)), true); + } + + private void Control_PopulateOnDemand(NavigationEventArgs args) + { + if (args.Node == null) + { + args.Node = Navigation.GetNavigationNode(args.ID, this.Control.ID); + } + + this.BuildNodes(args.Node); + } + } +} diff --git a/DNN Platform/Website/development.config b/DNN Platform/Website/development.config index d4b7617df2f..6ab918f3fe6 100644 --- a/DNN Platform/Website/development.config +++ b/DNN Platform/Website/development.config @@ -117,6 +117,11 @@ + + + + + @@ -149,7 +154,7 @@ --> - + - +