page.ts 39 KB

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