page.ts 36 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214
  1. /* eslint-disable @typescript-eslint/no-explicit-any */
  2. import mongoose, {
  3. Schema, Model, Document, AnyObject,
  4. } from 'mongoose';
  5. import mongoosePaginate from 'mongoose-paginate-v2';
  6. import uniqueValidator from 'mongoose-unique-validator';
  7. import escapeStringRegexp from 'escape-string-regexp';
  8. import nodePath from 'path';
  9. import { getOrCreateModel, pagePathUtils, pathUtils } from '@growi/core';
  10. import loggerFactory from '../../utils/logger';
  11. import Crowi from '../crowi';
  12. import { IPage } from '../../interfaces/page';
  13. import { getPageSchema, extractToAncestorsPaths, populateDataToShowRevision } from './obsolete-page';
  14. import { ObjectIdLike } from '~/server/interfaces/mongoose-utils';
  15. import { PageRedirectModel } from './page-redirect';
  16. const { addTrailingSlash } = pathUtils;
  17. const { isTopPage, collectAncestorPaths } = pagePathUtils;
  18. const logger = loggerFactory('growi:models:page');
  19. /*
  20. * define schema
  21. */
  22. const GRANT_PUBLIC = 1;
  23. const GRANT_RESTRICTED = 2;
  24. const GRANT_SPECIFIED = 3; // DEPRECATED
  25. const GRANT_OWNER = 4;
  26. const GRANT_USER_GROUP = 5;
  27. const PAGE_GRANT_ERROR = 1;
  28. const STATUS_PUBLISHED = 'published';
  29. const STATUS_DELETED = 'deleted';
  30. export interface PageDocument extends IPage, Document {}
  31. type TargetAndAncestorsResult = {
  32. targetAndAncestors: PageDocument[]
  33. rootPage: PageDocument
  34. }
  35. export type CreateMethod = (path: string, body: string, user, options) => Promise<PageDocument & { _id: any }>
  36. export interface PageModel extends Model<PageDocument> {
  37. [x: string]: any; // for obsolete methods
  38. createEmptyPagesByPaths(paths: string[], user: any | null, onlyMigratedAsExistingPages?: boolean, andFilter?): Promise<void>
  39. getParentAndFillAncestors(path: string, user): Promise<PageDocument & { _id: any }>
  40. findByIdsAndViewer(pageIds: ObjectIdLike[], user, userGroups?, includeEmpty?: boolean): Promise<PageDocument[]>
  41. findByPathAndViewer(path: string | null, user, userGroups?, useFindOne?: boolean, includeEmpty?: boolean): Promise<PageDocument[]>
  42. findTargetAndAncestorsByPathOrId(pathOrId: string): Promise<TargetAndAncestorsResult>
  43. findChildrenByParentPathOrIdAndViewer(parentPathOrId: string, user, userGroups?): Promise<PageDocument[]>
  44. findAncestorsChildrenByPathAndViewer(path: string, user, userGroups?): Promise<Record<string, PageDocument[]>>
  45. generateGrantCondition(
  46. user, userGroups, showAnyoneKnowsLink?: boolean, showPagesRestrictedByOwner?: boolean, showPagesRestrictedByGroup?: boolean,
  47. ): { $or: any[] }
  48. PageQueryBuilder: typeof PageQueryBuilder
  49. GRANT_PUBLIC
  50. GRANT_RESTRICTED
  51. GRANT_SPECIFIED
  52. GRANT_OWNER
  53. GRANT_USER_GROUP
  54. PAGE_GRANT_ERROR
  55. STATUS_PUBLISHED
  56. STATUS_DELETED
  57. }
  58. type IObjectId = mongoose.Types.ObjectId;
  59. const ObjectId = mongoose.Schema.Types.ObjectId;
  60. const schema = new Schema<PageDocument, PageModel>({
  61. parent: {
  62. type: ObjectId, ref: 'Page', index: true, default: null,
  63. },
  64. descendantCount: { type: Number, default: 0 },
  65. isEmpty: { type: Boolean, default: false },
  66. path: {
  67. type: String, required: true, index: true,
  68. },
  69. revision: { type: ObjectId, ref: 'Revision' },
  70. status: { type: String, default: STATUS_PUBLISHED, index: true },
  71. grant: { type: Number, default: GRANT_PUBLIC, index: true },
  72. grantedUsers: [{ type: ObjectId, ref: 'User' }],
  73. grantedGroup: { type: ObjectId, ref: 'UserGroup', index: true },
  74. creator: { type: ObjectId, ref: 'User', index: true },
  75. lastUpdateUser: { type: ObjectId, ref: 'User' },
  76. liker: [{ type: ObjectId, ref: 'User' }],
  77. seenUsers: [{ type: ObjectId, ref: 'User' }],
  78. commentCount: { type: Number, default: 0 },
  79. slackChannels: { type: String },
  80. pageIdOnHackmd: { type: String },
  81. revisionHackmdSynced: { type: ObjectId, ref: 'Revision' }, // the revision that is synced to HackMD
  82. hasDraftOnHackmd: { type: Boolean }, // set true if revision and revisionHackmdSynced are same but HackMD document has modified
  83. createdAt: { type: Date, default: new Date() },
  84. updatedAt: { type: Date, default: new Date() },
  85. deleteUser: { type: ObjectId, ref: 'User' },
  86. deletedAt: { type: Date },
  87. }, {
  88. toJSON: { getters: true },
  89. toObject: { getters: true },
  90. });
  91. // apply plugins
  92. schema.plugin(mongoosePaginate);
  93. schema.plugin(uniqueValidator);
  94. const hasSlash = (str: string): boolean => {
  95. return str.includes('/');
  96. };
  97. /*
  98. * Generate RegExp instance for one level lower path
  99. */
  100. const generateChildrenRegExp = (path: string): RegExp => {
  101. // https://regex101.com/r/laJGzj/1
  102. // ex. /any_level1
  103. if (isTopPage(path)) return new RegExp(/^\/[^/]+$/);
  104. // https://regex101.com/r/mrDJrx/1
  105. // ex. /parent/any_child OR /any_level1
  106. return new RegExp(`^${path}(\\/[^/]+)\\/?$`);
  107. };
  108. class PageQueryBuilder {
  109. query: any;
  110. constructor(query, includeEmpty = false) {
  111. this.query = query;
  112. if (!includeEmpty) {
  113. this.query = this.query
  114. .and({
  115. $or: [
  116. { isEmpty: false },
  117. { isEmpty: null }, // for v4 compatibility
  118. ],
  119. });
  120. }
  121. }
  122. /**
  123. * Used for filtering the pages at specified paths not to include unintentional pages.
  124. * @param pathsToFilter The paths to have additional filters as to be applicable
  125. * @returns PageQueryBuilder
  126. */
  127. addConditionToFilterByApplicableAncestors(pathsToFilter: string[]) {
  128. this.query = this.query
  129. .and(
  130. {
  131. $or: [
  132. { path: '/' },
  133. { path: { $in: pathsToFilter }, grant: GRANT_PUBLIC, status: STATUS_PUBLISHED },
  134. { path: { $in: pathsToFilter }, parent: { $ne: null }, status: STATUS_PUBLISHED },
  135. { path: { $nin: pathsToFilter }, status: STATUS_PUBLISHED },
  136. ],
  137. },
  138. );
  139. return this;
  140. }
  141. addConditionToExcludeTrashed() {
  142. this.query = this.query
  143. .and({
  144. $or: [
  145. { status: null },
  146. { status: STATUS_PUBLISHED },
  147. ],
  148. });
  149. return this;
  150. }
  151. /**
  152. * generate the query to find the pages '{path}/*' and '{path}' self.
  153. * If top page, return without doing anything.
  154. */
  155. addConditionToListWithDescendants(path: string, option?) {
  156. // No request is set for the top page
  157. if (isTopPage(path)) {
  158. return this;
  159. }
  160. const pathNormalized = pathUtils.normalizePath(path);
  161. const pathWithTrailingSlash = addTrailingSlash(path);
  162. const startsPattern = escapeStringRegexp(pathWithTrailingSlash);
  163. this.query = this.query
  164. .and({
  165. $or: [
  166. { path: pathNormalized },
  167. { path: new RegExp(`^${startsPattern}`) },
  168. ],
  169. });
  170. return this;
  171. }
  172. /**
  173. * generate the query to find the pages '{path}/*' (exclude '{path}' self).
  174. * If top page, return without doing anything.
  175. */
  176. addConditionToListOnlyDescendants(path, option) {
  177. // No request is set for the top page
  178. if (isTopPage(path)) {
  179. return this;
  180. }
  181. const pathWithTrailingSlash = addTrailingSlash(path);
  182. const startsPattern = escapeStringRegexp(pathWithTrailingSlash);
  183. this.query = this.query
  184. .and({ path: new RegExp(`^${startsPattern}`) });
  185. return this;
  186. }
  187. addConditionToListOnlyAncestors(path) {
  188. const pathNormalized = pathUtils.normalizePath(path);
  189. const ancestorsPaths = extractToAncestorsPaths(pathNormalized);
  190. this.query = this.query
  191. .and({
  192. path: {
  193. $in: ancestorsPaths,
  194. },
  195. });
  196. return this;
  197. }
  198. /**
  199. * generate the query to find pages that start with `path`
  200. *
  201. * In normal case, returns '{path}/*' and '{path}' self.
  202. * If top page, return without doing anything.
  203. *
  204. * *option*
  205. * Left for backward compatibility
  206. */
  207. addConditionToListByStartWith(path, option?) {
  208. // No request is set for the top page
  209. if (isTopPage(path)) {
  210. return this;
  211. }
  212. const startsPattern = escapeStringRegexp(path);
  213. this.query = this.query
  214. .and({ path: new RegExp(`^${startsPattern}`) });
  215. return this;
  216. }
  217. async addConditionForParentNormalization(user) {
  218. // determine UserGroup condition
  219. let userGroups;
  220. if (user != null) {
  221. const UserGroupRelation = mongoose.model('UserGroupRelation') as any; // TODO: Typescriptize model
  222. userGroups = await UserGroupRelation.findAllUserGroupIdsRelatedToUser(user);
  223. }
  224. const grantConditions: any[] = [
  225. { grant: null },
  226. { grant: GRANT_PUBLIC },
  227. ];
  228. if (user != null) {
  229. grantConditions.push(
  230. { grant: GRANT_OWNER, grantedUsers: user._id },
  231. );
  232. }
  233. if (userGroups != null && userGroups.length > 0) {
  234. grantConditions.push(
  235. { grant: GRANT_USER_GROUP, grantedGroup: { $in: userGroups } },
  236. );
  237. }
  238. this.query = this.query
  239. .and({
  240. $or: grantConditions,
  241. });
  242. return this;
  243. }
  244. async addConditionAsMigratablePages(user) {
  245. this.query = this.query
  246. .and({
  247. $or: [
  248. { grant: { $ne: GRANT_RESTRICTED } },
  249. { grant: { $ne: GRANT_SPECIFIED } },
  250. ],
  251. });
  252. this.addConditionAsNotMigrated();
  253. this.addConditionAsNonRootPage();
  254. this.addConditionToExcludeTrashed();
  255. await this.addConditionForParentNormalization(user);
  256. return this;
  257. }
  258. addConditionToFilteringByViewer(user, userGroups, showAnyoneKnowsLink = false, showPagesRestrictedByOwner = false, showPagesRestrictedByGroup = false) {
  259. const condition = generateGrantCondition(user, userGroups, showAnyoneKnowsLink, showPagesRestrictedByOwner, showPagesRestrictedByGroup);
  260. this.query = this.query
  261. .and(condition);
  262. return this;
  263. }
  264. addConditionToPagenate(offset, limit, sortOpt?) {
  265. this.query = this.query
  266. .sort(sortOpt).skip(offset).limit(limit); // eslint-disable-line newline-per-chained-call
  267. return this;
  268. }
  269. addConditionAsNonRootPage() {
  270. this.query = this.query.and({ path: { $ne: '/' } });
  271. return this;
  272. }
  273. addConditionAsNotMigrated() {
  274. this.query = this.query
  275. .and({ parent: null });
  276. return this;
  277. }
  278. addConditionAsMigrated() {
  279. this.query = this.query
  280. .and(
  281. {
  282. $or: [
  283. { parent: { $ne: null } },
  284. { path: '/' },
  285. ],
  286. },
  287. );
  288. return this;
  289. }
  290. /*
  291. * Add this condition when get any ancestor pages including the target's parent
  292. */
  293. addConditionToSortPagesByDescPath() {
  294. this.query = this.query.sort('-path');
  295. return this;
  296. }
  297. addConditionToSortPagesByAscPath() {
  298. this.query = this.query.sort('path');
  299. return this;
  300. }
  301. addConditionToMinimizeDataForRendering() {
  302. this.query = this.query.select('_id path isEmpty grant revision descendantCount');
  303. return this;
  304. }
  305. addConditionToListByPathsArray(paths) {
  306. this.query = this.query
  307. .and({
  308. path: {
  309. $in: paths,
  310. },
  311. });
  312. return this;
  313. }
  314. addConditionToListByPageIdsArray(pageIds) {
  315. this.query = this.query
  316. .and({
  317. _id: {
  318. $in: pageIds,
  319. },
  320. });
  321. return this;
  322. }
  323. addConditionToExcludeByPageIdsArray(pageIds) {
  324. this.query = this.query
  325. .and({
  326. _id: {
  327. $nin: pageIds,
  328. },
  329. });
  330. return this;
  331. }
  332. populateDataToList(userPublicFields) {
  333. this.query = this.query
  334. .populate({
  335. path: 'lastUpdateUser',
  336. select: userPublicFields,
  337. });
  338. return this;
  339. }
  340. populateDataToShowRevision(userPublicFields) {
  341. this.query = populateDataToShowRevision(this.query, userPublicFields);
  342. return this;
  343. }
  344. addConditionToFilteringByParentId(parentId) {
  345. this.query = this.query.and({ parent: parentId });
  346. return this;
  347. }
  348. }
  349. /**
  350. * Create empty pages if the page in paths didn't exist
  351. * @param onlyMigratedAsExistingPages Determine whether to include non-migrated pages as existing pages. If a page exists,
  352. * an empty page will not be created at that page's path.
  353. */
  354. schema.statics.createEmptyPagesByPaths = async function(paths: string[], user: any | null, onlyMigratedAsExistingPages = true, filter?): Promise<void> {
  355. const aggregationPipeline: any[] = [];
  356. // 1. Filter by paths
  357. aggregationPipeline.push({ $match: { path: { $in: paths } } });
  358. // 2. Normalized condition
  359. if (onlyMigratedAsExistingPages) {
  360. aggregationPipeline.push({
  361. $match: {
  362. $or: [
  363. { parent: { $ne: null } },
  364. { path: '/' },
  365. ],
  366. },
  367. });
  368. }
  369. // 3. Add custom pipeline
  370. if (filter != null) {
  371. aggregationPipeline.push({ $match: filter });
  372. }
  373. // 4. Add grant conditions
  374. let userGroups = null;
  375. if (user != null) {
  376. const UserGroupRelation = mongoose.model('UserGroupRelation') as any;
  377. userGroups = await UserGroupRelation.findAllUserGroupIdsRelatedToUser(user);
  378. }
  379. const grantCondition = this.generateGrantCondition(user, userGroups);
  380. aggregationPipeline.push({ $match: grantCondition });
  381. // Run aggregation
  382. const existingPages = await this.aggregate(aggregationPipeline);
  383. const existingPagePaths = existingPages.map(page => page.path);
  384. // paths to create empty pages
  385. const notExistingPagePaths = paths.filter(path => !existingPagePaths.includes(path));
  386. // insertMany empty pages
  387. try {
  388. await this.insertMany(notExistingPagePaths.map(path => ({ path, isEmpty: true })));
  389. }
  390. catch (err) {
  391. logger.error('Failed to insert empty pages.', err);
  392. throw err;
  393. }
  394. };
  395. schema.statics.createEmptyPage = async function(
  396. path: string, parent: any, descendantCount = 0, // TODO: improve type including IPage at https://redmine.weseek.co.jp/issues/86506
  397. ): Promise<PageDocument & { _id: any }> {
  398. if (parent == null) {
  399. throw Error('parent must not be null');
  400. }
  401. const Page = this;
  402. const page = new Page();
  403. page.path = path;
  404. page.isEmpty = true;
  405. page.parent = parent;
  406. page.descendantCount = descendantCount;
  407. return page.save();
  408. };
  409. /**
  410. * Replace an existing page with an empty page.
  411. * It updates the children's parent to the new empty page's _id.
  412. * @param exPage a page document to be replaced
  413. * @returns Promise<void>
  414. */
  415. schema.statics.replaceTargetWithPage = async function(exPage, pageToReplaceWith?, deleteExPageIfEmpty = false) {
  416. // find parent
  417. const parent = await this.findOne({ _id: exPage.parent });
  418. if (parent == null) {
  419. throw Error('parent to update does not exist. Prepare parent first.');
  420. }
  421. // create empty page at path
  422. const newTarget = pageToReplaceWith == null ? await this.createEmptyPage(exPage.path, parent, exPage.descendantCount) : pageToReplaceWith;
  423. // find children by ex-page _id
  424. const children = await this.find({ parent: exPage._id });
  425. // bulkWrite
  426. const operationForNewTarget = {
  427. updateOne: {
  428. filter: { _id: newTarget._id },
  429. update: {
  430. parent: parent._id,
  431. },
  432. },
  433. };
  434. const operationsForChildren = {
  435. updateMany: {
  436. filter: {
  437. _id: { $in: children.map(d => d._id) },
  438. },
  439. update: {
  440. parent: newTarget._id,
  441. },
  442. },
  443. };
  444. await this.bulkWrite([operationForNewTarget, operationsForChildren]);
  445. const isExPageEmpty = exPage.isEmpty;
  446. if (deleteExPageIfEmpty && isExPageEmpty) {
  447. await this.deleteOne({ _id: exPage._id });
  448. logger.warn('Deleted empty page since it was replaced with another page.');
  449. }
  450. return this.findById(newTarget._id);
  451. };
  452. /**
  453. * Find parent or create parent if not exists.
  454. * It also updates parent of ancestors
  455. * @param path string
  456. * @returns Promise<PageDocument>
  457. */
  458. schema.statics.getParentAndFillAncestors = async function(path: string, user): Promise<PageDocument> {
  459. const parentPath = nodePath.dirname(path);
  460. const builder1 = new PageQueryBuilder(this.find({ path: parentPath }), true);
  461. const pagesCanBeParent = await builder1
  462. .addConditionAsMigrated()
  463. .query
  464. .exec();
  465. if (pagesCanBeParent.length >= 1) {
  466. return pagesCanBeParent[0]; // the earliest page will be the result
  467. }
  468. /*
  469. * Fill parents if parent is null
  470. */
  471. const ancestorPaths = collectAncestorPaths(path); // paths of parents need to be created
  472. // just create ancestors with empty pages
  473. await this.createEmptyPagesByPaths(ancestorPaths, user);
  474. // find ancestors
  475. const builder2 = new PageQueryBuilder(this.find(), true);
  476. // avoid including not normalized pages
  477. builder2.addConditionToFilterByApplicableAncestors(ancestorPaths);
  478. const ancestors = await builder2
  479. .addConditionToListByPathsArray(ancestorPaths)
  480. .addConditionToSortPagesByDescPath()
  481. .query
  482. .exec();
  483. const ancestorsMap = new Map(); // Map<path, page>
  484. ancestors.forEach(page => !ancestorsMap.has(page.path) && ancestorsMap.set(page.path, page)); // the earlier element should be the true ancestor
  485. // bulkWrite to update ancestors
  486. const nonRootAncestors = ancestors.filter(page => !isTopPage(page.path));
  487. const operations = nonRootAncestors.map((page) => {
  488. const parentPath = nodePath.dirname(page.path);
  489. return {
  490. updateOne: {
  491. filter: {
  492. _id: page._id,
  493. },
  494. update: {
  495. parent: ancestorsMap.get(parentPath)._id,
  496. },
  497. },
  498. };
  499. });
  500. await this.bulkWrite(operations);
  501. const createdParent = ancestorsMap.get(parentPath);
  502. return createdParent;
  503. };
  504. // Utility function to add viewer condition to PageQueryBuilder instance
  505. const addViewerCondition = async(queryBuilder: PageQueryBuilder, user, userGroups = null): Promise<void> => {
  506. let relatedUserGroups = userGroups;
  507. if (user != null && relatedUserGroups == null) {
  508. const UserGroupRelation: any = mongoose.model('UserGroupRelation');
  509. relatedUserGroups = await UserGroupRelation.findAllUserGroupIdsRelatedToUser(user);
  510. }
  511. queryBuilder.addConditionToFilteringByViewer(user, relatedUserGroups, false);
  512. };
  513. /*
  514. * Find pages by ID and viewer.
  515. */
  516. schema.statics.findByIdsAndViewer = async function(pageIds: string[], user, userGroups?, includeEmpty?: boolean): Promise<PageDocument[]> {
  517. const baseQuery = this.find({ _id: { $in: pageIds } });
  518. const queryBuilder = new PageQueryBuilder(baseQuery, includeEmpty);
  519. await addViewerCondition(queryBuilder, user, userGroups);
  520. return queryBuilder.query.exec();
  521. };
  522. /*
  523. * Find a page by path and viewer. Pass false to useFindOne to use findOne method.
  524. */
  525. schema.statics.findByPathAndViewer = async function(
  526. path: string | null, user, userGroups = null, useFindOne = true, includeEmpty = false,
  527. ): Promise<PageDocument | PageDocument[] | null> {
  528. if (path == null) {
  529. throw new Error('path is required.');
  530. }
  531. const baseQuery = useFindOne ? this.findOne({ path }) : this.find({ path });
  532. const queryBuilder = new PageQueryBuilder(baseQuery, includeEmpty);
  533. await addViewerCondition(queryBuilder, user, userGroups);
  534. return queryBuilder.query.exec();
  535. };
  536. /*
  537. * Find all ancestor pages by path. When duplicate pages found, it uses the oldest page as a result
  538. * The result will include the target as well
  539. */
  540. schema.statics.findTargetAndAncestorsByPathOrId = async function(pathOrId: string, user, userGroups): Promise<TargetAndAncestorsResult> {
  541. let path;
  542. if (!hasSlash(pathOrId)) {
  543. const _id = pathOrId;
  544. const page = await this.findOne({ _id });
  545. path = page == null ? '/' : page.path;
  546. }
  547. else {
  548. path = pathOrId;
  549. }
  550. const ancestorPaths = collectAncestorPaths(path);
  551. ancestorPaths.push(path); // include target
  552. // Do not populate
  553. const queryBuilder = new PageQueryBuilder(this.find(), true);
  554. await addViewerCondition(queryBuilder, user, userGroups);
  555. const _targetAndAncestors: PageDocument[] = await queryBuilder
  556. .addConditionAsMigrated()
  557. .addConditionToListByPathsArray(ancestorPaths)
  558. .addConditionToMinimizeDataForRendering()
  559. .addConditionToSortPagesByDescPath()
  560. .query
  561. .lean()
  562. .exec();
  563. // no same path pages
  564. const ancestorsMap = new Map<string, PageDocument>();
  565. _targetAndAncestors.forEach(page => ancestorsMap.set(page.path, page));
  566. const targetAndAncestors = Array.from(ancestorsMap.values());
  567. const rootPage = targetAndAncestors[targetAndAncestors.length - 1];
  568. return { targetAndAncestors, rootPage };
  569. };
  570. /*
  571. * Find all children by parent's path or id. Using id should be prioritized
  572. */
  573. schema.statics.findChildrenByParentPathOrIdAndViewer = async function(parentPathOrId: string, user, userGroups = null): Promise<PageDocument[]> {
  574. let queryBuilder: PageQueryBuilder;
  575. if (hasSlash(parentPathOrId)) {
  576. const path = parentPathOrId;
  577. const regexp = generateChildrenRegExp(path);
  578. queryBuilder = new PageQueryBuilder(this.find({ path: { $regex: regexp } }), true);
  579. }
  580. else {
  581. const parentId = parentPathOrId;
  582. queryBuilder = new PageQueryBuilder(this.find({ parent: parentId } as any), true); // TODO: improve type
  583. }
  584. await addViewerCondition(queryBuilder, user, userGroups);
  585. return queryBuilder
  586. .addConditionToSortPagesByAscPath()
  587. .query
  588. .lean()
  589. .exec();
  590. };
  591. schema.statics.findAncestorsChildrenByPathAndViewer = async function(path: string, user, userGroups = null): Promise<Record<string, PageDocument[]>> {
  592. const ancestorPaths = isTopPage(path) ? ['/'] : collectAncestorPaths(path); // root path is necessary for rendering
  593. const regexps = ancestorPaths.map(path => new RegExp(generateChildrenRegExp(path))); // cannot use re2
  594. // get pages at once
  595. const queryBuilder = new PageQueryBuilder(this.find({ path: { $in: regexps } }), true);
  596. await addViewerCondition(queryBuilder, user, userGroups);
  597. const _pages = await queryBuilder
  598. .addConditionAsMigrated()
  599. .addConditionToMinimizeDataForRendering()
  600. .addConditionToSortPagesByAscPath()
  601. .query
  602. .lean()
  603. .exec();
  604. // mark target
  605. const pages = _pages.map((page: PageDocument & {isTarget?: boolean}) => {
  606. if (page.path === path) {
  607. page.isTarget = true;
  608. }
  609. return page;
  610. });
  611. /*
  612. * If any non-migrated page is found during creating the pathToChildren map, it will stop incrementing at that moment
  613. */
  614. const pathToChildren: Record<string, PageDocument[]> = {};
  615. const sortedPaths = ancestorPaths.sort((a, b) => a.length - b.length); // sort paths by path.length
  616. sortedPaths.every((path) => {
  617. const children = pages.filter(page => nodePath.dirname(page.path) === path);
  618. if (children.length === 0) {
  619. return false; // break when children do not exist
  620. }
  621. pathToChildren[path] = children;
  622. return true;
  623. });
  624. return pathToChildren;
  625. };
  626. /*
  627. * Utils from obsolete-page.js
  628. */
  629. async function pushRevision(pageData, newRevision, user) {
  630. await newRevision.save();
  631. pageData.revision = newRevision;
  632. pageData.lastUpdateUser = user;
  633. pageData.updatedAt = Date.now();
  634. return pageData.save();
  635. }
  636. /**
  637. * add/subtract descendantCount of pages with provided paths by increment.
  638. * increment can be negative number
  639. */
  640. schema.statics.incrementDescendantCountOfPageIds = async function(pageIds: ObjectIdLike[], increment: number): Promise<void> {
  641. await this.updateMany({ _id: { $in: pageIds } }, { $inc: { descendantCount: increment } });
  642. };
  643. /**
  644. * recount descendantCount of a page with the provided id and return it
  645. */
  646. schema.statics.recountDescendantCount = async function(id: ObjectIdLike):Promise<number> {
  647. const res = await this.aggregate(
  648. [
  649. {
  650. $match: {
  651. parent: id,
  652. },
  653. },
  654. {
  655. $project: {
  656. parent: 1,
  657. isEmpty: 1,
  658. descendantCount: 1,
  659. },
  660. },
  661. {
  662. $group: {
  663. _id: '$parent',
  664. sumOfDescendantCount: {
  665. $sum: '$descendantCount',
  666. },
  667. sumOfDocsCount: {
  668. $sum: {
  669. $cond: { if: { $eq: ['$isEmpty', true] }, then: 0, else: 1 }, // exclude isEmpty true page from sumOfDocsCount
  670. },
  671. },
  672. },
  673. },
  674. {
  675. $set: {
  676. descendantCount: {
  677. $sum: ['$sumOfDescendantCount', '$sumOfDocsCount'],
  678. },
  679. },
  680. },
  681. ],
  682. );
  683. return res.length === 0 ? 0 : res[0].descendantCount;
  684. };
  685. schema.statics.findAncestorsUsingParentRecursively = async function(pageId: ObjectIdLike, shouldIncludeTarget: boolean) {
  686. const self = this;
  687. const target = await this.findById(pageId);
  688. if (target == null) {
  689. throw Error('Target not found');
  690. }
  691. async function findAncestorsRecursively(target, ancestors = shouldIncludeTarget ? [target] : []) {
  692. const parent = await self.findOne({ _id: target.parent });
  693. if (parent == null) {
  694. return ancestors;
  695. }
  696. return findAncestorsRecursively(parent, [...ancestors, parent]);
  697. }
  698. return findAncestorsRecursively(target);
  699. };
  700. // TODO: write test code
  701. /**
  702. * Recursively removes empty pages at leaf position.
  703. * @param pageId ObjectIdLike
  704. * @returns Promise<void>
  705. */
  706. schema.statics.removeLeafEmptyPagesRecursively = async function(pageId: ObjectIdLike): Promise<void> {
  707. const self = this;
  708. const initialPage = await this.findById(pageId);
  709. if (initialPage == null) {
  710. return;
  711. }
  712. if (!initialPage.isEmpty) {
  713. return;
  714. }
  715. async function generatePageIdsToRemove(childPage, page, pageIds: ObjectIdLike[] = []): Promise<ObjectIdLike[]> {
  716. if (!page.isEmpty) {
  717. return pageIds;
  718. }
  719. const isChildrenOtherThanTargetExist = await self.exists({ _id: { $ne: childPage?._id }, parent: page._id });
  720. if (isChildrenOtherThanTargetExist) {
  721. return pageIds;
  722. }
  723. pageIds.push(page._id);
  724. const nextPage = await self.findById(page.parent);
  725. if (nextPage == null) {
  726. return pageIds;
  727. }
  728. return generatePageIdsToRemove(page, nextPage, pageIds);
  729. }
  730. const pageIdsToRemove = await generatePageIdsToRemove(null, initialPage);
  731. await this.deleteMany({ _id: { $in: pageIdsToRemove } });
  732. };
  733. schema.statics.normalizeDescendantCountById = async function(pageId) {
  734. const children = await this.find({ parent: pageId });
  735. const sumChildrenDescendantCount = children.map(d => d.descendantCount).reduce((c1, c2) => c1 + c2);
  736. const sumChildPages = children.filter(p => !p.isEmpty).length;
  737. return this.updateOne({ _id: pageId }, { $set: { descendantCount: sumChildrenDescendantCount + sumChildPages } }, { new: true });
  738. };
  739. schema.statics.takeOffFromTree = async function(pageId: ObjectIdLike) {
  740. return this.findByIdAndUpdate(pageId, { $set: { parent: null } });
  741. };
  742. schema.statics.removeEmptyPages = async function(pageIdsToNotRemove: ObjectIdLike[], paths: string[]): Promise<void> {
  743. await this.deleteMany({
  744. _id: {
  745. $nin: pageIdsToNotRemove,
  746. },
  747. path: {
  748. $in: paths,
  749. },
  750. isEmpty: true,
  751. });
  752. };
  753. schema.statics.PageQueryBuilder = PageQueryBuilder as any; // mongoose does not support constructor type as statics attrs type
  754. export function generateGrantCondition(
  755. user, userGroups, showAnyoneKnowsLink = false, showPagesRestrictedByOwner = false, showPagesRestrictedByGroup = false,
  756. ): { $or: any[] } {
  757. const grantConditions: AnyObject[] = [
  758. { grant: null },
  759. { grant: GRANT_PUBLIC },
  760. ];
  761. if (showAnyoneKnowsLink) {
  762. grantConditions.push({ grant: GRANT_RESTRICTED });
  763. }
  764. if (showPagesRestrictedByOwner) {
  765. grantConditions.push(
  766. { grant: GRANT_SPECIFIED },
  767. { grant: GRANT_OWNER },
  768. );
  769. }
  770. else if (user != null) {
  771. grantConditions.push(
  772. { grant: GRANT_SPECIFIED, grantedUsers: user._id },
  773. { grant: GRANT_OWNER, grantedUsers: user._id },
  774. );
  775. }
  776. if (showPagesRestrictedByGroup) {
  777. grantConditions.push(
  778. { grant: GRANT_USER_GROUP },
  779. );
  780. }
  781. else if (userGroups != null && userGroups.length > 0) {
  782. grantConditions.push(
  783. { grant: GRANT_USER_GROUP, grantedGroup: { $in: userGroups } },
  784. );
  785. }
  786. return {
  787. $or: grantConditions,
  788. };
  789. }
  790. schema.statics.generateGrantCondition = generateGrantCondition;
  791. export type PageCreateOptions = {
  792. format?: string
  793. grantUserGroupId?: ObjectIdLike
  794. grant?: number
  795. }
  796. /*
  797. * Merge obsolete page model methods and define new methods which depend on crowi instance
  798. */
  799. export default (crowi: Crowi): any => {
  800. let pageEvent;
  801. if (crowi != null) {
  802. pageEvent = crowi.event('page');
  803. }
  804. schema.statics.create = async function(path: string, body: string, user, options: PageCreateOptions = {}) {
  805. if (crowi.pageGrantService == null || crowi.configManager == null || crowi.pageService == null || crowi.pageOperationService == null) {
  806. throw Error('Crowi is not setup');
  807. }
  808. const isV5Compatible = crowi.configManager.getConfig('crowi', 'app:isV5Compatible');
  809. // v4 compatible process
  810. if (!isV5Compatible) {
  811. return this.createV4(path, body, user, options);
  812. }
  813. const canOperate = await crowi.pageOperationService.canOperate(false, null, path);
  814. if (!canOperate) {
  815. throw Error(`Cannot operate create to path "${path}" right now.`);
  816. }
  817. const Page = this;
  818. const Revision = crowi.model('Revision');
  819. const {
  820. format = 'markdown', grantUserGroupId,
  821. } = options;
  822. let grant = options.grant;
  823. // sanitize path
  824. path = crowi.xss.process(path); // eslint-disable-line no-param-reassign
  825. // throw if exists
  826. const isExist = (await this.count({ path, isEmpty: false })) > 0; // not validate empty page
  827. if (isExist) {
  828. throw new Error('Cannot create new page to existed path');
  829. }
  830. // force public
  831. if (isTopPage(path)) {
  832. grant = GRANT_PUBLIC;
  833. }
  834. // find an existing empty page
  835. const emptyPage = await Page.findOne({ path, isEmpty: true });
  836. /*
  837. * UserGroup & Owner validation
  838. */
  839. if (grant !== GRANT_RESTRICTED) {
  840. let isGrantNormalized = false;
  841. try {
  842. // It must check descendants as well if emptyTarget is not null
  843. const shouldCheckDescendants = emptyPage != null;
  844. const newGrantedUserIds = grant === GRANT_OWNER ? [user._id] as IObjectId[] : undefined;
  845. isGrantNormalized = await crowi.pageGrantService.isGrantNormalized(user, path, grant, newGrantedUserIds, grantUserGroupId, shouldCheckDescendants);
  846. }
  847. catch (err) {
  848. logger.error(`Failed to validate grant of page at "${path}" of grant ${grant}:`, err);
  849. throw err;
  850. }
  851. if (!isGrantNormalized) {
  852. throw Error('The selected grant or grantedGroup is not assignable to this page.');
  853. }
  854. }
  855. /*
  856. * update empty page if exists, if not, create a new page
  857. */
  858. let page;
  859. if (emptyPage != null && grant !== GRANT_RESTRICTED) {
  860. page = emptyPage;
  861. const descendantCount = await this.recountDescendantCount(page._id);
  862. page.descendantCount = descendantCount;
  863. page.isEmpty = false;
  864. }
  865. else {
  866. page = new Page();
  867. }
  868. page.path = path;
  869. page.creator = user;
  870. page.lastUpdateUser = user;
  871. page.status = STATUS_PUBLISHED;
  872. // set parent to null when GRANT_RESTRICTED
  873. const isGrantRestricted = grant === GRANT_RESTRICTED;
  874. if (isTopPage(path) || isGrantRestricted) {
  875. page.parent = null;
  876. }
  877. else {
  878. const parent = await Page.getParentAndFillAncestors(path, user);
  879. page.parent = parent._id;
  880. }
  881. page.applyScope(user, grant, grantUserGroupId);
  882. let savedPage = await page.save();
  883. /*
  884. * After save
  885. */
  886. // Delete PageRedirect if exists
  887. const PageRedirect = mongoose.model('PageRedirect') as unknown as PageRedirectModel;
  888. try {
  889. await PageRedirect.deleteOne({ fromPath: path });
  890. logger.warn(`Deleted page redirect after creating a new page at path "${path}".`);
  891. }
  892. catch (err) {
  893. // no throw
  894. logger.error('Failed to delete PageRedirect');
  895. }
  896. const newRevision = Revision.prepareRevision(savedPage, body, null, user, { format });
  897. savedPage = await pushRevision(savedPage, newRevision, user);
  898. await savedPage.populateDataToShowRevision();
  899. pageEvent.emit('create', savedPage, user);
  900. // update descendantCount asynchronously
  901. await crowi.pageService.updateDescendantCountOfAncestors(savedPage._id, 1, false);
  902. return savedPage;
  903. };
  904. const shouldUseUpdatePageV4 = (grant:number, isV5Compatible:boolean, isOnTree:boolean): boolean => {
  905. const isRestricted = grant === GRANT_RESTRICTED;
  906. return !isRestricted && (!isV5Compatible || !isOnTree);
  907. };
  908. schema.statics.updatePage = async function(pageData, body, previousBody, user, options = {}) {
  909. if (crowi.configManager == null || crowi.pageGrantService == null || crowi.pageService == null) {
  910. throw Error('Crowi is not set up');
  911. }
  912. const wasOnTree = pageData.parent != null || isTopPage(pageData.path);
  913. const exParent = pageData.parent;
  914. const isV5Compatible = crowi.configManager.getConfig('crowi', 'app:isV5Compatible');
  915. const shouldUseV4Process = shouldUseUpdatePageV4(pageData.grant, isV5Compatible, wasOnTree);
  916. if (shouldUseV4Process) {
  917. // v4 compatible process
  918. return this.updatePageV4(pageData, body, previousBody, user, options);
  919. }
  920. const Revision = mongoose.model('Revision') as any; // TODO: Typescriptize model
  921. const grant = options.grant || pageData.grant; // use the previous data if absence
  922. const grantUserGroupId: undefined | ObjectIdLike = options.grantUserGroupId ?? pageData.grantedGroup?._id.toString();
  923. const isSyncRevisionToHackmd = options.isSyncRevisionToHackmd;
  924. const grantedUserIds = pageData.grantedUserIds || [user._id];
  925. const shouldBeOnTree = grant !== GRANT_RESTRICTED;
  926. const isChildrenExist = await this.count({ path: new RegExp(`^${escapeStringRegexp(addTrailingSlash(pageData.path))}`), parent: { $ne: null } });
  927. const newPageData = pageData;
  928. if (shouldBeOnTree) {
  929. let isGrantNormalized = false;
  930. try {
  931. isGrantNormalized = await crowi.pageGrantService.isGrantNormalized(user, pageData.path, grant, grantedUserIds, grantUserGroupId, true);
  932. }
  933. catch (err) {
  934. logger.error(`Failed to validate grant of page at "${pageData.path}" of grant ${grant}:`, err);
  935. throw err;
  936. }
  937. if (!isGrantNormalized) {
  938. throw Error('The selected grant or grantedGroup is not assignable to this page.');
  939. }
  940. if (!wasOnTree) {
  941. const newParent = await this.getParentAndFillAncestors(newPageData.path, user);
  942. newPageData.parent = newParent._id;
  943. }
  944. }
  945. else {
  946. if (wasOnTree && isChildrenExist) {
  947. // Update children's parent with new parent
  948. const newParentForChildren = await this.createEmptyPage(pageData.path, pageData.parent, pageData.descendantCount);
  949. await this.updateMany(
  950. { parent: pageData._id },
  951. { parent: newParentForChildren._id },
  952. );
  953. }
  954. newPageData.parent = null;
  955. newPageData.descendantCount = 0;
  956. }
  957. newPageData.applyScope(user, grant, grantUserGroupId);
  958. // update existing page
  959. let savedPage = await newPageData.save();
  960. const newRevision = await Revision.prepareRevision(newPageData, body, previousBody, user);
  961. savedPage = await pushRevision(savedPage, newRevision, user);
  962. await savedPage.populateDataToShowRevision();
  963. if (isSyncRevisionToHackmd) {
  964. savedPage = await this.syncRevisionToHackmd(savedPage);
  965. }
  966. pageEvent.emit('update', savedPage, user);
  967. // Update ex children's parent
  968. if (!wasOnTree && shouldBeOnTree) {
  969. const emptyPageAtSamePath = await this.findOne({ path: pageData.path, isEmpty: true }); // this page is necessary to find children
  970. if (isChildrenExist) {
  971. if (emptyPageAtSamePath != null) {
  972. // Update children's parent with new parent
  973. await this.updateMany(
  974. { parent: emptyPageAtSamePath._id },
  975. { parent: savedPage._id },
  976. );
  977. }
  978. }
  979. await this.findOneAndDelete({ path: pageData.path, isEmpty: true }); // delete here
  980. }
  981. // Sub operation
  982. // 1. Update descendantCount
  983. const shouldPlusDescCount = !wasOnTree && shouldBeOnTree;
  984. const shouldMinusDescCount = wasOnTree && !shouldBeOnTree;
  985. if (shouldPlusDescCount) {
  986. await crowi.pageService.updateDescendantCountOfAncestors(newPageData._id, 1, false);
  987. const newDescendantCount = await this.recountDescendantCount(newPageData._id);
  988. await this.updateOne({ _id: newPageData._id }, { descendantCount: newDescendantCount });
  989. }
  990. else if (shouldMinusDescCount) {
  991. // Update from parent. Parent is null if newPageData.grant is RESTRECTED.
  992. if (newPageData.grant === GRANT_RESTRICTED) {
  993. await crowi.pageService.updateDescendantCountOfAncestors(exParent, -1, true);
  994. }
  995. }
  996. // 2. Delete unnecessary empty pages
  997. const shouldRemoveLeafEmpPages = wasOnTree && !isChildrenExist;
  998. if (shouldRemoveLeafEmpPages) {
  999. await this.removeLeafEmptyPagesRecursively(exParent);
  1000. }
  1001. return savedPage;
  1002. };
  1003. // add old page schema methods
  1004. const pageSchema = getPageSchema(crowi);
  1005. schema.methods = { ...pageSchema.methods, ...schema.methods };
  1006. schema.statics = { ...pageSchema.statics, ...schema.statics };
  1007. return getOrCreateModel<PageDocument, PageModel>('Page', schema as any); // TODO: improve type
  1008. };