Exemple #1
0
        static bool TryLoadAzureEnvVar(this WordPressConfig config)
        {
            return(HandleEnvironmentVar(
                       Environment.GetEnvironmentVariable("MYSQLCONNSTR_localdb"),
                       (name, value) =>
            {
                if (name.Equals("Data Source", StringComparison.OrdinalIgnoreCase))
                {
                    config.DbHost = value;
                    return true;
                }

                if (name.Equals("User Id", StringComparison.OrdinalIgnoreCase))
                {
                    config.DbUser = value;
                    return true;
                }

                if (name.Equals("Password", StringComparison.OrdinalIgnoreCase))
                {
                    config.DbPassword = value;
                    return true;
                }

                if (name.Equals("Database", StringComparison.OrdinalIgnoreCase))
                {
                    config.DbName = value;
                    return true;
                }

                return false;
            }));
        }
        static bool TryLoadAzureEnvVar(this WordPressConfig config, string connectionString)
        {
            return(ParseEnvironmentVar(
                       connectionString,
                       (name, value) =>
            {
                if (name.Equals("Data Source", StringComparison.OrdinalIgnoreCase))
                {
                    config.DbHost = value;
                    return true;
                }

                if (name.Equals("User Id", StringComparison.OrdinalIgnoreCase))
                {
                    config.DbUser = value;
                    return true;
                }

                if (name.Equals("Password", StringComparison.OrdinalIgnoreCase))
                {
                    config.DbPassword = value;
                    return true;
                }

                if (name.Equals("Database", StringComparison.OrdinalIgnoreCase))
                {
                    config.DbName = value;
                    return true;
                }

                return false;
            }));
        }
Exemple #3
0
        /// <summary>
        /// Defines WordPress configuration constants and initializes runtime before proceeding to <c>index.php</c>.
        /// </summary>
        static void Apply(Context ctx, WordPressConfig config, WpLoader loader)
        {
            // see wp-config.php:

            // WordPress Database Table prefix.
            ctx.Globals["table_prefix"] = (PhpValue)config.DbTablePrefix; // $table_prefix  = 'wp_';

            // SALT
            ctx.DefineConstant("AUTH_KEY", (PhpValue)config.SALT.AUTH_KEY);
            ctx.DefineConstant("SECURE_AUTH_KEY", (PhpValue)config.SALT.SECURE_AUTH_KEY);
            ctx.DefineConstant("LOGGED_IN_KEY", (PhpValue)config.SALT.LOGGED_IN_KEY);
            ctx.DefineConstant("NONCE_KEY", (PhpValue)config.SALT.NONCE_KEY);
            ctx.DefineConstant("AUTH_SALT", (PhpValue)config.SALT.AUTH_SALT);
            ctx.DefineConstant("SECURE_AUTH_SALT", (PhpValue)config.SALT.SECURE_AUTH_SALT);
            ctx.DefineConstant("LOGGED_IN_SALT", (PhpValue)config.SALT.LOGGED_IN_SALT);
            ctx.DefineConstant("NONCE_SALT", (PhpValue)config.SALT.NONCE_SALT);

            // Additional constants
            if (config.Constants != null)
            {
                foreach (var pair in config.Constants)
                {
                    ctx.DefineConstant(pair.Key, pair.Value);
                }
            }

            // $peachpie-wp-loader : WpLoader
            ctx.Globals["peachpie_wp_loader"] = PhpValue.FromClass(loader);
        }
Exemple #4
0
        private void TryToDeleteImages()
        {
            lblStatus.Text = "Rolling back...";

            WordPressConfig config = new WordPressConfig("https://www.raywenderlich.com", txtUsername.Text, txtPassword.Text);

            try
            {
                // Something went wrong, delete all uploaded images
                for (var i = 0; i < _imageIdList.Count; i++)
                {
                    int  id      = _imageIdList[i];
                    bool deleted = WordPressConnector.Delete(id);
                    progressUpload.Value--;

                    if (!deleted)
                    {
                        MessageBox.Show("Couldn't delete image: " + ImageUploadData.ImageUrls[i]);
                    }
                }
            }
            catch (Exception exception)
            {
                Console.WriteLine(exception);
                MessageBox.Show("Image rollback failed. Please delete the remaining images manually.");
                return;
            }

            MessageBox.Show("Rollback succesfull!");
        }
Exemple #5
0
        /// <summary>
        /// Loads configuration from <see cref="IConfigureOptions{WordPressConfig}"/> service.
        /// </summary>
        public static WordPressConfig LoadFromOptions(this WordPressConfig config, IServiceProvider services)
        {
            if (services.TryGetService <IConfigureOptions <WordPressConfig> >(out var configservice))
            {
                configservice.Configure(config);
            }

            return(config);
        }
Exemple #6
0
        /// <summary>
        /// Loads settings from a well-known environment variables.
        /// This overrides values set previously.
        /// </summary>
        public static WordPressConfig LoadFromEnvironment(this WordPressConfig config, IServiceProvider services)
        {
            if (string.IsNullOrEmpty(config.DbHost) || config.DbHost == "localhost")
            {
                // load known environment variables
                TryLoadAzureEnvVar(config);
            }

            //
            return(config);
        }
Exemple #7
0
        /// <summary>
        /// Adds implicit configuration values.
        /// </summary>
        public static WordPressConfig LoadDefaults(this WordPressConfig config)
        {
            var containers = config.CompositionContainers
                             //.WithAssembly(Assembly.GetEntryAssembly()) // {app} itself
                             //.WithAssembly(typeof(Provider).Assembly)
                             .WithAssembly(Assembly.Load("PeachPied.WordPress.NuGetPlugins"))
            ;

            (config.LegacyPluginAssemblies ??= new List <string>()).AddRange(DefaultPhpAssemblies);

            return(config);
        }
        /// <summary>
        /// Adds implicit configuration values.
        /// Loads containers from dependency context.
        /// </summary>
        public static WordPressConfig LoadDefaults(this WordPressConfig config)
        {
            var PeachPiedWordPress = typeof(WP).Assembly.GetName().Name;                  // "PeachPied.WordPress"
            var WordPressStandard  = typeof(Standard.WpStandard).Assembly.GetName().Name; // "PeachPied.WordPress.Standard"

            // reads dependencies from app's DependencyContext
            foreach (var lib in DependencyContext.Default.RuntimeLibraries)
            {
                if (lib.Type != "package" && lib.Type != "project")
                {
                    continue;
                }

                bool HasPeachPiedWordPress = false;
                bool HasWordPressStandard  = false;

                for (int dep = 0; dep < lib.Dependencies.Count; dep++)
                {
                    var depname = lib.Dependencies[dep].Name;
                    HasPeachPiedWordPress |= depname == PeachPiedWordPress;
                    HasWordPressStandard  |= depname == WordPressStandard;
                }

                if (HasWordPressStandard || HasPeachPiedWordPress)
                {
                    var ass = Assembly.Load(new AssemblyName(lib.Name));
                    if (ass.GetType(Pchp.Core.Context.ScriptInfo.ScriptTypeName) != null)
                    {
                        // PHP assembly
                        //(config.LegacyPluginAssemblies ??= new List<string>()).Add(ass.FullName);
                        Pchp.Core.Context.AddScriptReference(ass);
                    }
                    else
                    {
                        // not PHP assembly
                        // add as MEF composition container
                        config.CompositionContainers.WithAssembly(ass);
                    }
                }
            }

            //config.CompositionContainers
            //    //.WithAssembly(Assembly.GetEntryAssembly()) // {app} itself
            //    //.WithAssembly(typeof(Provider).Assembly)
            //    .WithAssembly(Assembly.Load("PeachPied.WordPress.NuGetPlugins"))
            //    ;

            //
            return(config);
        }
Exemple #9
0
        /// <summary>
        /// Loads configuration from appsettings file (<see cref="IConfiguration"/>).
        /// </summary>
        public static WordPressConfig LoadFromSettings(this WordPressConfig config, IServiceProvider services)
        {
            if (config == null)
            {
                throw new ArgumentNullException(nameof(config));
            }

            if (services.TryGetService <IConfiguration>(out var appconfig))
            {
                appconfig.GetSection("WordPress").Bind(config);
            }

            //
            return(config);
        }
Exemple #10
0
        /// <summary>
        /// Defines WordPress configuration constants and initializes runtime before proceeding to <c>index.php</c>.
        /// </summary>
        static void Apply(Context ctx, WordPressConfig config, WpLoader loader)
        {
            // see wp-config.php:

            // WordPress Database Table prefix.
            ctx.Globals["table_prefix"] = (PhpValue)config.DbTablePrefix; // $table_prefix  = 'wp_';

            // SALT
            ctx.DefineConstant("AUTH_KEY", (PhpValue)config.SALT.AUTH_KEY);
            ctx.DefineConstant("SECURE_AUTH_KEY", (PhpValue)config.SALT.SECURE_AUTH_KEY);
            ctx.DefineConstant("LOGGED_IN_KEY", (PhpValue)config.SALT.LOGGED_IN_KEY);
            ctx.DefineConstant("NONCE_KEY", (PhpValue)config.SALT.NONCE_KEY);
            ctx.DefineConstant("AUTH_SALT", (PhpValue)config.SALT.AUTH_SALT);
            ctx.DefineConstant("SECURE_AUTH_SALT", (PhpValue)config.SALT.SECURE_AUTH_SALT);
            ctx.DefineConstant("LOGGED_IN_SALT", (PhpValue)config.SALT.LOGGED_IN_SALT);
            ctx.DefineConstant("NONCE_SALT", (PhpValue)config.SALT.NONCE_SALT);

            if (!string.IsNullOrEmpty(config.SiteUrl))
            {
                ctx.DefineConstant("WP_SITEURL", config.SiteUrl);
            }

            if (!string.IsNullOrEmpty(config.HomeUrl))
            {
                ctx.DefineConstant("WP_HOME", config.HomeUrl);
            }

            // Additional constants
            if (config.Constants != null)
            {
                foreach (var pair in config.Constants)
                {
                    ctx.DefineConstant(pair.Key, pair.Value);
                }
            }

            // $peachpie-wp-loader : WpLoader
            ctx.Globals["peachpie_wp_loader"] = PhpValue.FromClass(loader);

            // workaround HTTPS under proxy,
            // set $_SERVER['HTTPS'] = 'on'
            // https://wordpress.org/support/article/administration-over-ssl/#using-a-reverse-proxy
            if (ctx.IsWebApplication && ctx.GetHttpContext().Request.Headers["X-Forwarded-Proto"] == "https")
            {
                ctx.Server["HTTPS"] = "on";
            }
        }
Exemple #11
0
        /// <summary>
        /// Loads configuration from appsettings file (<see cref="IConfiguration"/>).
        /// </summary>
        public static WordPressConfig LoadFromSettings(this WordPressConfig config, IServiceProvider services)
        {
            if (config == null)
            {
                config = CreateDefault();
            }

            var appconfig = (IConfiguration)services.GetService(typeof(IConfiguration));

            if (appconfig != null)
            {
                appconfig.GetSection("WordPress").Bind(config);
            }

            //
            return(config);
        }
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, IConfiguration configuration)
        {
            // settings:
            var wpconfig = new WordPressConfig();

            configuration.GetSection("WordPress").Bind(wpconfig);

            //
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseWordPress(wpconfig);

            app.UseDefaultFiles();
        }
Exemple #13
0
        /// <summary>
        /// Installs WordPress middleware.
        /// </summary>
        /// <param name="app">The application builder.</param>
        /// <param name="path">Physical location of wordpress folder. Can be absolute or relative to the current directory.</param>
        public static IApplicationBuilder UseWordPress(this IApplicationBuilder app, string path = null)
        {
            // load options
            var options = new WordPressConfig()
                          .LoadFromSettings(app.ApplicationServices)    // appsettings.json
                          .LoadFromEnvironment(app.ApplicationServices) // environment variables (known cloud hosts)
                          .LoadFromOptions(app.ApplicationServices)     // IConfigureOptions<WordPressConfig> service
                          .LoadDefaults();                              //

            // get WP_HOME and WP_SITE
            string sitepath = null;
            string homepath = null;

            if (Uri.TryCreate(options.SiteUrl, UriKind.Absolute, out var siteuri))
            {
                sitepath = siteuri.LocalPath;
            }

            if (Uri.TryCreate(options.HomeUrl, UriKind.Absolute, out var homeuri))
            {
                homepath = homeuri.LocalPath;
            }

            bool siteProceed = false;

            // use when the wordpress path is a part of the requested path
            app.UseWhen(
                context =>
            {
                siteProceed = string.IsNullOrEmpty(sitepath) || context.Request.Path.Value.StartsWith(sitepath);
                return(siteProceed);
            },
                app => app.UsePathBase(sitepath).InstallWordPress(options, path, sitepath)
                );

            // use when the home path is a part of the requested path
            app.UseWhen(
                context => !siteProceed && (string.IsNullOrEmpty(homepath) || context.Request.Path.Value.StartsWith(homepath)),
                app => app.UsePathBase(homepath).InstallWordPress(options, path, sitepath)
                );

            //
            return(app);
        }
Exemple #14
0
        /// <summary>
        /// Installs WordPress middleware.
        /// </summary>
        /// <param name="app">The application builder.</param>
        /// <param name="path">Physical location of wordpress folder. Can be absolute or relative to the current directory.</param>
        public static IApplicationBuilder UseWordPress(this IApplicationBuilder app, string path = null)
        {
            // wordpress root path:
            if (path == null)
            {
                // bin/wordpress
                path = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location) + "/wordpress";

                if (Directory.Exists(path) == false)
                {
                    // cwd/wordpress
                    path = Path.GetDirectoryName(Directory.GetCurrentDirectory()) + "/wordpress";

                    if (Directory.Exists(path) == false)
                    {
                        // cwd/../wordpress
                        path = Path.GetDirectoryName(Path.GetDirectoryName(Directory.GetCurrentDirectory())) + "/wordpress";
                    }
                }
            }

            var root      = System.IO.Path.GetFullPath(path);
            var fprovider = new PhysicalFileProvider(root);

            // log exceptions:
            app.UseDiagnostic();

            // load options
            var options = new WordPressConfig()
                          .LoadFromSettings(app.ApplicationServices)    // appsettings.json
                          .LoadFromEnvironment(app.ApplicationServices) // environment variables (known cloud hosts)
                          .LoadFromOptions(app.ApplicationServices)     // IConfigureOptions<WordPressConfig> service
                          .LoadDefaults();                              //

            // list of plugins:
            var plugins = new WpPluginContainer(options.PluginContainer);

            // response caching:
            if (options.EnableResponseCaching)
            {
                // var cachepolicy = new WpResponseCachingPolicyProvider();
                // var cachekey = app.ApplicationServices.GetService<WpResponseCachingKeyProvider>();

                var cachepolicy = new WpResponseCachePolicy();
                plugins.Add(cachepolicy);

                // app.UseMiddleware<ResponseCachingMiddleware>(cachepolicy, cachekey);
                app.UseMiddleware <WpResponseCacheMiddleware>(new MemoryCache(new MemoryCacheOptions {
                }), cachepolicy);
            }

            var wploader = new WpLoader(plugins:
                                        CompositionHelpers.GetPlugins(options.CompositionContainers.CreateContainer(), app.ApplicationServices)
                                        .Concat(plugins.GetPlugins(app.ApplicationServices)));

            // url rewriting:
            app.UseRewriter(new RewriteOptions().Add(context => ShortUrlRule(context, fprovider)));

            // update globals used by WordPress:
            WpStandard.DB_HOST     = options.DbHost;
            WpStandard.DB_NAME     = options.DbName;
            WpStandard.DB_PASSWORD = options.DbPassword;
            WpStandard.DB_USER     = options.DbUser;

            //
            var env = app.ApplicationServices.GetService <IHostingEnvironment>();

            WpStandard.WP_DEBUG = options.Debug || env.IsDevelopment();

            // handling php files:
            var startup = new Action <Context>(ctx => Apply(ctx, options, wploader));

            app.UsePhp(new PhpRequestOptions()
            {
                ScriptAssembliesName = options.LegacyPluginAssemblies?.ToArray(),
                BeforeRequest        = startup,
                RootPath             = root,
            });

            // static files
            app.UseStaticFiles(new StaticFileOptions()
            {
                FileProvider = fprovider
            });

            // fire wp-cron.php asynchronously
            WpCronScheduler.StartScheduler(startup, TimeSpan.FromSeconds(60));

            //
            return(app);
        }
 public static void InitializeWordPress(string username, string password)
 {
     _config = new WordPressConfig("https://www.raywenderlich.com", username, password);
 }
Exemple #16
0
        private static IApplicationBuilder InstallWordPress(this IApplicationBuilder app, WordPressConfig options, string path = null, string siteurl = null)
        {
            // wordpress root path:
            if (path == null)
            {
                // bin/wordpress
                path = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location) + "/wordpress";

                if (Directory.Exists(path) == false)
                {
                    // cwd/wordpress
                    path = Path.GetDirectoryName(Directory.GetCurrentDirectory()) + "/wordpress";

                    if (Directory.Exists(path) == false)
                    {
                        // cwd/../wordpress
                        path = Path.GetDirectoryName(Path.GetDirectoryName(Directory.GetCurrentDirectory())) + "/wordpress";
                    }
                }
            }

            var root      = System.IO.Path.GetFullPath(path);
            var fprovider = new PhysicalFileProvider(root);

            // log exceptions:
            app.UseDiagnostic();

            // list of plugins:
            var plugins = new WpPluginContainer(options.PluginContainer);

            // response caching:
            if (options.EnableResponseCaching)
            {
                // var cachepolicy = new WpResponseCachingPolicyProvider();
                // var cachekey = app.ApplicationServices.GetService<WpResponseCachingKeyProvider>();

                var cachepolicy = new WpResponseCachePolicy();
                plugins.Add(cachepolicy);

                // app.UseMiddleware<ResponseCachingMiddleware>(cachepolicy, cachekey);
                app.UseMiddleware <WpResponseCacheMiddleware>(new MemoryCache(new MemoryCacheOptions {
                }), cachepolicy);
            }

            // if (options.LegacyPluginAssemblies != null)
            // {
            //     options.LegacyPluginAssemblies.ForEach(name => Context.AddScriptReference(Assembly.Load(new AssemblyName(name))));
            // }

            var wploader = new WpLoader(plugins:
                                        CompositionHelpers.GetPlugins(options.CompositionContainers.CreateContainer(), app.ApplicationServices, root)
                                        .Concat(plugins.GetPlugins(app.ApplicationServices)));

            // url rewriting:
            bool multisite        = options.Multisite.Enable;
            bool subdomainInstall = options.Multisite.SubdomainInstall;

            if (options.Constants != null && !multisite && !subdomainInstall)
            {
                // using constants instead MultisiteData
                if (options.Constants.TryGetValue("MULTISITE", out string multi))
                {
                    multisite = bool.TryParse(multi, out bool multiConverted) && multiConverted;
                }
                if (options.Constants.TryGetValue("SUBDOMAIN_INSTALL", out string domain))
                {
                    subdomainInstall = bool.TryParse(domain, out bool domainConverted) && domainConverted;
                }
            }
            app.UseRewriter(new RewriteOptions().Add(context => ShortUrlRule(context, fprovider, multisite, subdomainInstall, siteurl)));

            // update globals used by WordPress:
            WpStandard.DB_HOST     = options.DbHost;
            WpStandard.DB_NAME     = options.DbName;
            WpStandard.DB_PASSWORD = options.DbPassword;
            WpStandard.DB_USER     = options.DbUser;

            //
            var env = app.ApplicationServices.GetService <IHostingEnvironment>();

            WpStandard.WP_DEBUG = options.Debug || env.IsDevelopment();

            // handling php files:
            var startup = new Action <Context>(ctx =>
            {
                Apply(ctx, options, wploader);
            });

            // app.UsePhp(
            //     prefix: default, // NOTE: maybe we can handle only index.php and wp-admin/*.php ?
            //     configureContext: startup,
            //     rootPath: root);

            app.UsePhp(new PhpRequestOptions()
            {
                ScriptAssembliesName = options.LegacyPluginAssemblies?.ToArray(),
                BeforeRequest        = startup,
                RootPath             = root,
            });

            // static files
            app.UseStaticFiles(new StaticFileOptions()
            {
                FileProvider = fprovider
            });

            // fire wp-cron.php asynchronously
            WpCronScheduler.StartScheduler(startup, TimeSpan.FromSeconds(120), root);

            return(app);
        }