UNPKG

@rnaga/wp-node

Version:

👉 **[View Full Documentation at rnaga.github.io/wp-node →](https://rnaga.github.io/wp-node/)**

396 lines (395 loc) • 16.1 kB
"use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __importStar = (this && this.__importStar) || (function () { var ownKeys = function(o) { ownKeys = Object.getOwnPropertyNames || function (o) { var ar = []; for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; return ar; }; return ownKeys(o); }; return function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); __setModuleDefault(result, mod); return result; }; })(); var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.Installer = void 0; const common_1 = require("../common"); const config_1 = require("../config"); const constants_1 = require("../constants"); const database_1 = __importDefault(require("../database")); const component_1 = require("../decorators/component"); const transactions_1 = require("../transactions"); const val = __importStar(require("../validators")); const components_1 = require("./components"); const current_1 = require("./current"); const options_1 = require("./options"); const schema_1 = require("./schema"); const tables_1 = require("./tables"); const link_util_1 = require("./utils/link.util"); const query_util_1 = require("./utils/query.util"); const trx_util_1 = require("./utils/trx.util"); const user_util_1 = require("./utils/user.util"); let Installer = class Installer { components; database; config; trxUtil; schema; queryUtil; linkUtil; constructor(components, database, config, trxUtil, schema, queryUtil, linkUtil) { this.components = components; this.database = database; this.config = config; this.trxUtil = trxUtil; this.schema = schema; this.queryUtil = queryUtil; this.linkUtil = linkUtil; } // wp_is_site_initialized async isBlogInitialized(blogId) { const tables = this.components.get(tables_1.Tables); tables.index = blogId; return await this.database.hasTable(tables.get("posts")); } // helper for seederTrx.populateSite async initializeSite(...args) { const seeder = this.components.get(transactions_1.SeederTrx); const options = this.components.get(options_1.Options); await seeder.populateSite(...args); const queryUtil = this.components.get(query_util_1.QueryUtil); const site = await queryUtil.sites((query) => { const { column } = query.alias; query.builder.orderBy(column("site", "id"), "desc").first(); if (args[0].domain) { query.where("domain", args[0].domain); } if (args[0].path) { query.where("path", args[0].path); } }, val.database.wpSite); if (!site) { throw new Error(`Site not found`); } // Update sitemeta for non-main site if (site.id > 1) { const siteAdmins = []; if (args[0].email) { const email = args[0].email; const users = await this.queryUtil.users((query) => { query.where("user_email", email); }); if (users) { siteAdmins.push(users[0].user_login); } } let siteUrlScheme = "http"; const defaultSiteUrl = await options.get("siteurl", { siteId: 1, }); if (defaultSiteUrl && defaultSiteUrl.startsWith("https")) { siteUrlScheme = "https"; } const siteUrl = common_1.formatting.untrailingslashit(`${siteUrlScheme}://${args[0].domain}${args[0].path}`); const metaTrx = this.components.get(transactions_1.MetaTrx); await metaTrx.bulkUpsertObject("site", site.id, { site_admins: siteAdmins, siteurl: siteUrl, }); } return site.id; } async uninitializeSite(siteId, newSiteId, options) { const newBlogStatus = { public: options?.newBlogStatus?.public ?? 0, archived: options?.newBlogStatus?.archived ?? 1, deleted: options?.newBlogStatus?.deleted ?? 1, }; const queryUtil = this.components.get(query_util_1.QueryUtil); const site = await queryUtil.sites((query) => { query.where("id", siteId).builder.first(); }, val.database.wpSite); if (!site) { throw new Error("Site not found"); } if (1 === site.id) { throw new Error("Main site can't be uninitialized"); } const blogs = (await queryUtil.blogs((query) => { query.where("site_id", siteId); })) ?? []; const blogTrx = this.components.get(transactions_1.BlogTrx); for (const blog of blogs) { if (newSiteId) { await blogTrx.changeSite(blog.blog_id, newSiteId); await blogTrx.upsert({ blog_id: blog.blog_id, ...newBlogStatus, }); continue; } await blogTrx.remove(blog.blog_id); } const siteTrx = this.components.get(transactions_1.SiteTrx); await siteTrx.remove(siteId); return true; } // wp_initialize_site // // Note: Don't directly call this method to create a new blog // Use blogTrx.upsert instead async initializeBlog(blogId, args) { const optionsComponent = this.components.get(options_1.Options); if (typeof blogId !== "number") { throw new Error("Site ID must not be empty."); } const blog = await this.queryUtil.blogs((query) => { query.where("blog_id", blogId).builder.first(); }, val.database.wpBlogs); if (!blog) { throw new Error(`Site with the ID does not exist. - ${blogId}`); } if (await this.isBlogInitialized(blogId)) { throw new Error(`The site appears to be already initialized. - ${blogId}`); } const site = await this.queryUtil.sites((query) => { query.where("id", blog.site_id).builder.first(); }, val.database.wpSite); const current = this.components.get(current_1.Current); let siteId; if (site) { siteId = site.id; } else { if (!current.site?.props.site.id) { throw new Error(`Site not found - ${blog.site_id}`); } siteId = current.site.props.site.id; } const currentBlogId = current.blogId; if (currentBlogId !== blogId) { await current.switchSite(siteId, blogId); } const { userId = 0, title = `Site ${site?.id}`, options = {}, meta = undefined, } = args ?? {}; // Set up the database tables. await this.schema.build("blog"); let homeScheme = "http"; let siteUrlScheme = "http"; if (!this.config.isSubdomainInstall()) { const homeUrl = await this.linkUtil.getHomeUrl({ blogId, }); //if ("https" === new URL(homeUrl).protocol.replace(/:$/, "")) { if (homeUrl.startsWith("https")) { homeScheme = "https"; } const siteUrl = await optionsComponent.get("siteurl", { siteId, }); //if (siteUrl && "https" === new URL(siteUrl).protocol.replace(/:$/, "")) { if (siteUrl && siteUrl.startsWith("https")) { siteUrlScheme = "https"; } } let uploadPath = await optionsComponent.get("upload_path", { blogId, }); const msFilesRewriting = await optionsComponent.get("ms_files_rewriting", { siteId, }); if (msFilesRewriting) { uploadPath = `${this.config.config.multisite.uploadBlogsDir}/${siteId}/files`; } // Populate the site's options. await this.trxUtil.seeder.populateOptions({ home: common_1.formatting.untrailingslashit(`${homeScheme}://${blog.domain}${blog.path}`), siteUrl: common_1.formatting.untrailingslashit(`${siteUrlScheme}://${blog.domain}${blog.path}`), blogname: common_1.formatting.unslash(title), admin_email: "", upload_path: uploadPath, blog_public: blog.public, WPLANG: await optionsComponent.get("WPLANG", { siteId }), ...options, }); // Populate the site's roles. await this.trxUtil.seeder.populateRoles(); // Populate metadata for the site. if (meta) { await this.trxUtil.meta.bulkUpsertObject("site", siteId, meta); } const tables = this.components.get(tables_1.Tables); tables.index = blogId; // Remove all permissions that may exist for the site. await this.trxUtil.meta.remove("user", { key: `${tables.prefix}user_level`, deleteAll: true, }); await this.trxUtil.meta.remove("user", { key: `${tables.prefix}capabilities`, deleteAll: true, }); await this.trxUtil.seeder.populateContent(userId); // Set the site administrator. await this.trxUtil.blog.addUser(blogId, userId, "administrator"); const userUtil = this.components.get(user_util_1.UserUtil); const user = await userUtil.get(userId); const role = await user.role(); const primaryBlog = await this.queryUtil.meta("user", (query) => { query.withIds([userId]).withKeys(["primary_blog"]); }); if (!role.isSuperAdmin() && !primaryBlog) { await this.trxUtil.meta.upsert("user", userId, "primary_blog", blogId); } if (currentBlogId !== blogId) { await current.restorePrevious(); } return true; } // wp_uninitialize_site // // Note: Don't directly call this method to delete a blog // Use blogTrx.remove instead async uninitializeBlog(blogId) { if (typeof blogId !== "number") { throw new Error("Site ID must not be empty."); } const blog = await this.queryUtil.blogs((query) => { query.where("blog_id", blogId).builder.first(); }, val.database.wpBlogs); if (!blog) { throw new Error(`Site with the ID does not exist. - ${blogId}`); } if (!(await this.isBlogInitialized(blogId))) { throw new Error(`The site appears to be already uninitialized. - ${blogId}`); } const users = await this.queryUtil.users((query) => { query.withBlogIds([blogId]); }); if (users) { for (const user of users) { await this.trxUtil.blog.removeUser(blogId, user.ID); } } const current = this.components.get(current_1.Current); const currentBlogId = current.blogId; if (currentBlogId != blogId) { await current.switchSite(blog.site_id, blogId); } await this.schema.dropBlog(blogId); // Delete directories if (currentBlogId != blogId) { await current.restorePrevious(); } return true; } // wp_install /** * * Note: Requires siteUrl besides what's originally required for wp_install * * @param args - The arguments for the installation * @returns */ async install(args) { let { userPassword = undefined } = args; const { siteUrl, blogTitle, userName, userEmail, isPublic, language = undefined, } = args; // check_database_version - wp_check_mysql_version(); await this.schema.build("all"); await this.trxUtil.seeder.populateOptions({ siteUrl, }); await this.trxUtil.seeder.populateRoles(); await this.trxUtil.options.update("blogname", blogTitle); await this.trxUtil.options.update("admin_email", userEmail); await this.trxUtil.options.update("blog_public", isPublic ? "1" : "0"); // Freshness of site - in the future, this could get more specific about actions taken, perhaps. await this.trxUtil.options.update("fresh_site", "1"); if (language) { await this.trxUtil.options.update("WPLANG", language); } await this.trxUtil.options.update("siteurl", siteUrl); if (!isPublic) { await this.trxUtil.options.update("default_pingback_flag", 0); } /* * Create default user. If the user already exists, the user tables are * being shared among sites. Just set the role in that case. */ let userId = ((await this.queryUtil.users((query) => { query.where("user_login", userName).builder.first(); }, val.database.wpUsers)) ?? {})?.ID; if (!userId) { let userUpsert = { user_login: userName, user_pass: userPassword, user_email: userEmail, user_url: siteUrl, role: "administrator", }; if (!userPassword) { userPassword = (0, common_1.generatePassword)(12, false); userUpsert = { ...userUpsert, user_pass: userPassword, meta_input: { default_password_nag: "true", }, }; } userId = await this.trxUtil.user.upsert(userUpsert); if (!userId) { throw new Error(`Failed to create user - ${userEmail} ${userPassword}`); } } await this.trxUtil.seeder.populateContent(userId); return { url: siteUrl, userId, password: userPassword, }; } }; exports.Installer = Installer; exports.Installer = Installer = __decorate([ (0, component_1.component)({ scope: constants_1.Scope.Transient }), __metadata("design:paramtypes", [components_1.Components, database_1.default, config_1.Config, trx_util_1.TrxUtil, schema_1.Schema, query_util_1.QueryUtil, link_util_1.LinkUtil]) ], Installer);