page.ts 33 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145
  1. /* eslint-disable @typescript-eslint/no-explicit-any */
  2. import assert from 'assert';
  3. import nodePath from 'path';
  4. import {
  5. type IPage,
  6. GroupType, type HasObjectId,
  7. } from '@growi/core';
  8. import { getIdForRef, isPopulated } from '@growi/core/dist/interfaces';
  9. import { isTopPage, hasSlash } from '@growi/core/dist/utils/page-path-utils';
  10. import { addTrailingSlash, normalizePath } from '@growi/core/dist/utils/path-utils';
  11. import escapeStringRegexp from 'escape-string-regexp';
  12. import type {
  13. Model, Document, AnyObject,
  14. HydratedDocument,
  15. Types,
  16. } from 'mongoose';
  17. import mongoose, { Schema } from 'mongoose';
  18. import mongoosePaginate from 'mongoose-paginate-v2';
  19. import uniqueValidator from 'mongoose-unique-validator';
  20. import type { ExternalUserGroupDocument } from '~/features/external-user-group/server/models/external-user-group';
  21. import ExternalUserGroupRelation from '~/features/external-user-group/server/models/external-user-group-relation';
  22. import type { IOptionsForCreate } from '~/interfaces/page';
  23. import type { ObjectIdLike } from '~/server/interfaces/mongoose-utils';
  24. import loggerFactory from '../../utils/logger';
  25. import { collectAncestorPaths } from '../util/collect-ancestor-paths';
  26. import { getOrCreateModel } from '../util/mongoose-utils';
  27. import { getPageSchema, extractToAncestorsPaths, populateDataToShowRevision } from './obsolete-page';
  28. import type { UserGroupDocument } from './user-group';
  29. import UserGroupRelation from './user-group-relation';
  30. const logger = loggerFactory('growi:models:page');
  31. /*
  32. * define schema
  33. */
  34. const GRANT_PUBLIC = 1;
  35. const GRANT_RESTRICTED = 2;
  36. const GRANT_SPECIFIED = 3; // DEPRECATED
  37. const GRANT_OWNER = 4;
  38. const GRANT_USER_GROUP = 5;
  39. const PAGE_GRANT_ERROR = 1;
  40. const STATUS_PUBLISHED = 'published';
  41. const STATUS_DELETED = 'deleted';
  42. export interface PageDocument extends IPage, Document<Types.ObjectId> {
  43. [x:string]: any // for obsolete methods
  44. getLatestRevisionBodyLength(): Promise<number | null | undefined>
  45. calculateAndUpdateLatestRevisionBodyLength(this: PageDocument): Promise<void>
  46. }
  47. type TargetAndAncestorsResult = {
  48. targetAndAncestors: PageDocument[]
  49. rootPage: PageDocument
  50. }
  51. type PaginatedPages = {
  52. pages: PageDocument[],
  53. totalCount: number,
  54. limit: number,
  55. offset: number
  56. }
  57. export type CreateMethod = (path: string, body: string, user, options: IOptionsForCreate) => Promise<HydratedDocument<PageDocument>>
  58. export interface PageModel extends Model<PageDocument> {
  59. [x: string]: any; // for obsolete static methods
  60. findByIdAndViewer(pageId: ObjectIdLike, user, userGroups?, includeEmpty?: boolean): Promise<HydratedDocument<PageDocument> | null>
  61. findByIdsAndViewer(
  62. pageIds: ObjectIdLike[], user, userGroups?, includeEmpty?: boolean, includeAnyoneWithTheLink?: boolean,
  63. ): Promise<HydratedDocument<PageDocument>[]>
  64. findByPath(path: string, includeEmpty?: boolean): Promise<HydratedDocument<PageDocument> | null>
  65. findByPathAndViewer(path: string | null, user, userGroups?, useFindOne?: true, includeEmpty?: boolean): Promise<HydratedDocument<PageDocument> | null>
  66. findByPathAndViewer(path: string | null, user, userGroups?, useFindOne?: false, includeEmpty?: boolean): Promise<HydratedDocument<PageDocument>[]>
  67. countByPathAndViewer(path: string | null, user, userGroups?, includeEmpty?:boolean): Promise<number>
  68. findParentByPath(path: string | null): Promise<HydratedDocument<PageDocument> | null>
  69. findTargetAndAncestorsByPathOrId(pathOrId: string): Promise<TargetAndAncestorsResult>
  70. findRecentUpdatedPages(path: string, user, option, includeEmpty?: boolean): Promise<PaginatedPages>
  71. generateGrantCondition(
  72. user, userGroups: ObjectIdLike[] | null, includeAnyoneWithTheLink?: boolean, showPagesRestrictedByOwner?: boolean, showPagesRestrictedByGroup?: boolean,
  73. ): { $or: any[] }
  74. findNonEmptyClosestAncestor(path: string): Promise<HydratedDocument<PageDocument> | null>
  75. findNotEmptyParentByPathRecursively(path: string): Promise<HydratedDocument<PageDocument> | null>
  76. removeLeafEmptyPagesRecursively(pageId: ObjectIdLike): Promise<void>
  77. findTemplate(path: string): Promise<{
  78. templateBody?: string,
  79. templateTags?: string[],
  80. }>
  81. removeGroupsToDeleteFromPages(pages: PageDocument[], groupsToDelete: UserGroupDocument[] | ExternalUserGroupDocument[]): Promise<void>
  82. PageQueryBuilder: typeof PageQueryBuilder
  83. GRANT_PUBLIC
  84. GRANT_RESTRICTED
  85. GRANT_SPECIFIED
  86. GRANT_OWNER
  87. GRANT_USER_GROUP
  88. PAGE_GRANT_ERROR
  89. STATUS_PUBLISHED
  90. STATUS_DELETED
  91. }
  92. const schema = new Schema<PageDocument, PageModel>({
  93. parent: {
  94. type: Schema.Types.ObjectId, ref: 'Page', index: true, default: null,
  95. },
  96. descendantCount: { type: Number, default: 0 },
  97. isEmpty: { type: Boolean, default: false },
  98. path: {
  99. type: String, required: true, index: true,
  100. },
  101. revision: { type: Schema.Types.ObjectId, ref: 'Revision' },
  102. latestRevisionBodyLength: { type: Number },
  103. status: { type: String, default: STATUS_PUBLISHED, index: true },
  104. grant: { type: Number, default: GRANT_PUBLIC, index: true },
  105. grantedUsers: [{ type: Schema.Types.ObjectId, ref: 'User' }],
  106. grantedGroups: {
  107. type: [{
  108. type: {
  109. type: String,
  110. enum: Object.values(GroupType),
  111. required: true,
  112. default: 'UserGroup',
  113. },
  114. item: {
  115. type: Schema.Types.ObjectId,
  116. refPath: 'grantedGroups.type',
  117. required: true,
  118. index: true,
  119. },
  120. }],
  121. validate: [function(arr) {
  122. if (arr == null) return true;
  123. const uniqueItemValues = new Set(arr.map(e => e.item));
  124. return arr.length === uniqueItemValues.size;
  125. }, 'grantedGroups contains non unique item'],
  126. default: [],
  127. required: true,
  128. },
  129. creator: { type: Schema.Types.ObjectId, ref: 'User', index: true },
  130. lastUpdateUser: { type: Schema.Types.ObjectId, ref: 'User' },
  131. liker: [{ type: Schema.Types.ObjectId, ref: 'User' }],
  132. seenUsers: [{ type: Schema.Types.ObjectId, ref: 'User' }],
  133. commentCount: { type: Number, default: 0 },
  134. expandContentWidth: { type: Boolean },
  135. wip: { type: Boolean },
  136. ttlTimestamp: { type: Date },
  137. updatedAt: { type: Date, default: Date.now }, // Do not use timetamps for updatedAt because it breaks 'updateMetadata: false' option
  138. deleteUser: { type: Schema.Types.ObjectId, ref: 'User' },
  139. deletedAt: { type: Date },
  140. }, {
  141. timestamps: { createdAt: true, updatedAt: false },
  142. toJSON: { getters: true },
  143. toObject: { getters: true },
  144. });
  145. // indexes
  146. schema.index({ createdAt: 1 });
  147. schema.index({ updatedAt: 1 });
  148. // apply plugins
  149. schema.plugin(mongoosePaginate);
  150. schema.plugin(uniqueValidator);
  151. export class PageQueryBuilder {
  152. query: any;
  153. constructor(query, includeEmpty = false) {
  154. this.query = query;
  155. if (!includeEmpty) {
  156. this.query = this.query
  157. .and({
  158. $or: [
  159. { isEmpty: false },
  160. { isEmpty: null }, // for v4 compatibility
  161. ],
  162. });
  163. }
  164. }
  165. /**
  166. * Used for filtering the pages at specified paths not to include unintentional pages.
  167. * @param pathsToFilter The paths to have additional filters as to be applicable
  168. * @returns PageQueryBuilder
  169. */
  170. addConditionToFilterByApplicableAncestors(pathsToFilter: string[]): PageQueryBuilder {
  171. this.query = this.query
  172. .and(
  173. {
  174. $or: [
  175. { path: '/' },
  176. { path: { $in: pathsToFilter }, grant: GRANT_PUBLIC, status: STATUS_PUBLISHED },
  177. { path: { $in: pathsToFilter }, parent: { $ne: null }, status: STATUS_PUBLISHED },
  178. { path: { $nin: pathsToFilter }, status: STATUS_PUBLISHED },
  179. ],
  180. },
  181. );
  182. return this;
  183. }
  184. addConditionToExcludeTrashed(): PageQueryBuilder {
  185. this.query = this.query
  186. .and({
  187. $or: [
  188. { status: null },
  189. { status: STATUS_PUBLISHED },
  190. ],
  191. });
  192. return this;
  193. }
  194. addConditionToExcludeWipPage(): PageQueryBuilder {
  195. this.query = this.query
  196. .and({
  197. $or: [
  198. { wip: undefined },
  199. { wip: false },
  200. ],
  201. });
  202. return this;
  203. }
  204. /**
  205. * generate the query to find the pages '{path}/*' and '{path}' self.
  206. * If top page, return without doing anything.
  207. */
  208. addConditionToListWithDescendants(path: string, option?): PageQueryBuilder {
  209. // No request is set for the top page
  210. if (isTopPage(path)) {
  211. return this;
  212. }
  213. const pathNormalized = normalizePath(path);
  214. const pathWithTrailingSlash = addTrailingSlash(path);
  215. const startsPattern = escapeStringRegexp(pathWithTrailingSlash);
  216. this.query = this.query
  217. .and({
  218. $or: [
  219. { path: pathNormalized },
  220. { path: new RegExp(`^${startsPattern}`) },
  221. ],
  222. });
  223. return this;
  224. }
  225. /**
  226. * generate the query to find the pages '{path}/*' (exclude '{path}' self).
  227. */
  228. addConditionToListOnlyDescendants(path: string): PageQueryBuilder {
  229. // exclude the target page
  230. this.query = this.query.and({ path: { $ne: path } });
  231. if (isTopPage(path)) {
  232. return this;
  233. }
  234. const pathWithTrailingSlash = addTrailingSlash(path);
  235. const startsPattern = escapeStringRegexp(pathWithTrailingSlash);
  236. this.query = this.query
  237. .and(
  238. { path: new RegExp(`^${startsPattern}`) },
  239. );
  240. return this;
  241. }
  242. addConditionToListOnlyAncestors(path: string): PageQueryBuilder {
  243. const pathNormalized = normalizePath(path);
  244. const ancestorsPaths = extractToAncestorsPaths(pathNormalized);
  245. this.query = this.query
  246. // exclude the target page
  247. .and({ path: { $ne: path } })
  248. .and(
  249. { path: { $in: ancestorsPaths } },
  250. );
  251. return this;
  252. }
  253. /**
  254. * generate the query to find pages that start with `path`
  255. *
  256. * In normal case, returns '{path}/*' and '{path}' self.
  257. * If top page, return without doing anything.
  258. *
  259. * *option*
  260. * Left for backward compatibility
  261. */
  262. addConditionToListByStartWith(str: string): PageQueryBuilder {
  263. const path = normalizePath(str);
  264. // No request is set for the top page
  265. if (isTopPage(path)) {
  266. return this;
  267. }
  268. const startsPattern = escapeStringRegexp(path);
  269. this.query = this.query
  270. .and({ path: new RegExp(`^${startsPattern}`) });
  271. return this;
  272. }
  273. addConditionToListByNotStartWith(str: string): PageQueryBuilder {
  274. const path = normalizePath(str);
  275. // No request is set for the top page
  276. if (isTopPage(path)) {
  277. return this;
  278. }
  279. const startsPattern = escapeStringRegexp(str);
  280. this.query = this.query
  281. .and({ path: new RegExp(`^(?!${startsPattern}).*$`) });
  282. return this;
  283. }
  284. addConditionToListByMatch(str: string): PageQueryBuilder {
  285. // No request is set for "/"
  286. if (str === '/') {
  287. return this;
  288. }
  289. const match = escapeStringRegexp(str);
  290. this.query = this.query
  291. .and({ path: new RegExp(`^(?=.*${match}).*$`) });
  292. return this;
  293. }
  294. addConditionToListByNotMatch(str: string): PageQueryBuilder {
  295. // No request is set for "/"
  296. if (str === '/') {
  297. return this;
  298. }
  299. const match = escapeStringRegexp(str);
  300. this.query = this.query
  301. .and({ path: new RegExp(`^(?!.*${match}).*$`) });
  302. return this;
  303. }
  304. async addConditionForParentNormalization(user): Promise<PageQueryBuilder> {
  305. // determine UserGroup condition
  306. const userGroups = user != null ? [
  307. ...(await UserGroupRelation.findAllUserGroupIdsRelatedToUser(user)),
  308. ...(await ExternalUserGroupRelation.findAllUserGroupIdsRelatedToUser(user)),
  309. ] : null;
  310. const grantConditions: any[] = [
  311. { grant: null },
  312. { grant: GRANT_PUBLIC },
  313. ];
  314. if (user != null) {
  315. grantConditions.push(
  316. { grant: GRANT_OWNER, grantedUsers: user._id },
  317. );
  318. }
  319. if (userGroups != null && userGroups.length > 0) {
  320. grantConditions.push(
  321. {
  322. grant: GRANT_USER_GROUP,
  323. grantedGroups: { $elemMatch: { item: { $in: userGroups } } },
  324. },
  325. );
  326. }
  327. this.query = this.query
  328. .and({
  329. $or: grantConditions,
  330. });
  331. return this;
  332. }
  333. async addConditionAsMigratablePages(user): Promise<PageQueryBuilder> {
  334. this.query = this.query
  335. .and({
  336. $or: [
  337. { grant: { $ne: GRANT_RESTRICTED } },
  338. { grant: { $ne: GRANT_SPECIFIED } },
  339. ],
  340. });
  341. this.addConditionAsRootOrNotOnTree();
  342. this.addConditionAsNonRootPage();
  343. this.addConditionToExcludeTrashed();
  344. await this.addConditionForParentNormalization(user);
  345. return this;
  346. }
  347. // add viewer condition to PageQueryBuilder instance
  348. async addViewerCondition(user, userGroups = null, includeAnyoneWithTheLink = false): Promise<PageQueryBuilder> {
  349. const relatedUserGroups = (user != null && userGroups == null) ? [
  350. ...(await UserGroupRelation.findAllUserGroupIdsRelatedToUser(user)),
  351. ...(await ExternalUserGroupRelation.findAllUserGroupIdsRelatedToUser(user)),
  352. ] : userGroups;
  353. this.addConditionToFilteringByViewer(user, relatedUserGroups, includeAnyoneWithTheLink);
  354. return this;
  355. }
  356. addConditionToFilteringByViewer(
  357. user, userGroups: ObjectIdLike[] | null, includeAnyoneWithTheLink = false, showPagesRestrictedByOwner = false, showPagesRestrictedByGroup = false,
  358. ): PageQueryBuilder {
  359. const condition = generateGrantCondition(user, userGroups, includeAnyoneWithTheLink, showPagesRestrictedByOwner, showPagesRestrictedByGroup);
  360. this.query = this.query
  361. .and(condition);
  362. return this;
  363. }
  364. addConditionForSystemDeletion(): PageQueryBuilder {
  365. const condition = generateGrantConditionForSystemDeletion();
  366. this.query = this.query.and(condition);
  367. return this;
  368. }
  369. addConditionToPagenate(offset, limit, sortOpt?): PageQueryBuilder {
  370. this.query = this.query
  371. .sort(sortOpt).skip(offset).limit(limit); // eslint-disable-line newline-per-chained-call
  372. return this;
  373. }
  374. addConditionAsNonRootPage(): PageQueryBuilder {
  375. this.query = this.query.and({ path: { $ne: '/' } });
  376. return this;
  377. }
  378. addConditionAsRootOrNotOnTree(): PageQueryBuilder {
  379. this.query = this.query
  380. .and({ parent: null });
  381. return this;
  382. }
  383. addConditionAsOnTree(): PageQueryBuilder {
  384. this.query = this.query
  385. .and(
  386. {
  387. $or: [
  388. { parent: { $ne: null } },
  389. { path: '/' },
  390. ],
  391. },
  392. );
  393. return this;
  394. }
  395. /*
  396. * Add this condition when get any ancestor pages including the target's parent
  397. */
  398. addConditionToSortPagesByDescPath(): PageQueryBuilder {
  399. this.query = this.query.sort('-path');
  400. return this;
  401. }
  402. addConditionToSortPagesByAscPath(): PageQueryBuilder {
  403. this.query = this.query.sort('path');
  404. return this;
  405. }
  406. addConditionToMinimizeDataForRendering(): PageQueryBuilder {
  407. this.query = this.query.select('_id path isEmpty grant revision descendantCount');
  408. return this;
  409. }
  410. addConditionToListByPathsArray(paths): PageQueryBuilder {
  411. this.query = this.query
  412. .and({
  413. path: {
  414. $in: paths,
  415. },
  416. });
  417. return this;
  418. }
  419. addConditionToListByPageIdsArray(pageIds): PageQueryBuilder {
  420. this.query = this.query
  421. .and({
  422. _id: {
  423. $in: pageIds,
  424. },
  425. });
  426. return this;
  427. }
  428. addConditionToExcludeByPageIdsArray(pageIds): PageQueryBuilder {
  429. this.query = this.query
  430. .and({
  431. _id: {
  432. $nin: pageIds,
  433. },
  434. });
  435. return this;
  436. }
  437. populateDataToList(userPublicFields): PageQueryBuilder {
  438. this.query = this.query
  439. .populate({
  440. path: 'lastUpdateUser',
  441. select: userPublicFields,
  442. });
  443. return this;
  444. }
  445. populateDataToShowRevision(userPublicFields): PageQueryBuilder {
  446. this.query = populateDataToShowRevision(this.query, userPublicFields);
  447. return this;
  448. }
  449. addConditionToFilteringByParentId(parentId): PageQueryBuilder {
  450. this.query = this.query.and({ parent: parentId });
  451. return this;
  452. }
  453. }
  454. schema.statics.createEmptyPage = async function(
  455. path: string, parent: any, descendantCount = 0, // TODO: improve type including IPage at https://redmine.weseek.co.jp/issues/86506
  456. ): Promise<PageDocument & { _id: any }> {
  457. if (parent == null) {
  458. throw Error('parent must not be null');
  459. }
  460. const Page = this;
  461. const page = new Page();
  462. page.path = path;
  463. page.isEmpty = true;
  464. page.parent = parent;
  465. page.descendantCount = descendantCount;
  466. return page.save();
  467. };
  468. /**
  469. * Replace an existing page with an empty page.
  470. * It updates the children's parent to the new empty page's _id.
  471. * @param exPage a page document to be replaced
  472. * @returns Promise<void>
  473. */
  474. schema.statics.replaceTargetWithPage = async function(exPage, pageToReplaceWith?, deleteExPageIfEmpty = false) {
  475. // find parent
  476. const parent = await this.findOne({ _id: exPage.parent });
  477. if (parent == null) {
  478. throw Error('parent to update does not exist. Prepare parent first.');
  479. }
  480. // create empty page at path
  481. const newTarget = pageToReplaceWith == null ? await this.createEmptyPage(exPage.path, parent, exPage.descendantCount) : pageToReplaceWith;
  482. // find children by ex-page _id
  483. const children = await this.find({ parent: exPage._id });
  484. // bulkWrite
  485. const operationForNewTarget = {
  486. updateOne: {
  487. filter: { _id: newTarget._id },
  488. update: {
  489. parent: parent._id,
  490. },
  491. },
  492. };
  493. const operationsForChildren = {
  494. updateMany: {
  495. filter: {
  496. _id: { $in: children.map(d => d._id) },
  497. },
  498. update: {
  499. parent: newTarget._id,
  500. },
  501. },
  502. };
  503. await this.bulkWrite([operationForNewTarget, operationsForChildren]);
  504. const isExPageEmpty = exPage.isEmpty;
  505. if (deleteExPageIfEmpty && isExPageEmpty) {
  506. await this.deleteOne({ _id: exPage._id });
  507. logger.warn('Deleted empty page since it was replaced with another page.');
  508. }
  509. return this.findById(newTarget._id);
  510. };
  511. /*
  512. * Find pages by ID and viewer.
  513. */
  514. schema.statics.findByIdsAndViewer = async function(
  515. pageIds: string[], user, userGroups?, includeEmpty?: boolean, includeAnyoneWithTheLink?: boolean,
  516. ): Promise<PageDocument[]> {
  517. const baseQuery = this.find({ _id: { $in: pageIds } });
  518. const queryBuilder = new PageQueryBuilder(baseQuery, includeEmpty);
  519. await queryBuilder.addViewerCondition(user, userGroups, includeAnyoneWithTheLink);
  520. return queryBuilder.query.exec();
  521. };
  522. /*
  523. * Find a page by path and viewer. Pass true to useFindOne to use findOne method.
  524. */
  525. schema.statics.findByPathAndViewer = async function(
  526. path: string | null, user, userGroups = null, useFindOne = false, includeEmpty = false,
  527. ): Promise<(PageDocument | PageDocument[]) & HasObjectId | 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 includeAnyoneWithTheLink = useFindOne;
  533. const queryBuilder = new PageQueryBuilder(baseQuery, includeEmpty);
  534. await queryBuilder.addViewerCondition(user, userGroups, includeAnyoneWithTheLink);
  535. return queryBuilder.query.exec();
  536. };
  537. schema.statics.countByPathAndViewer = async function(path: string | null, user, userGroups = null, includeEmpty = false): Promise<number> {
  538. if (path == null) {
  539. throw new Error('path is required.');
  540. }
  541. const baseQuery = this.count({ path });
  542. const queryBuilder = new PageQueryBuilder(baseQuery, includeEmpty);
  543. await queryBuilder.addViewerCondition(user, userGroups);
  544. return queryBuilder.query.exec();
  545. };
  546. schema.statics.findRecentUpdatedPages = async function(
  547. path: string, user, options, includeEmpty = false,
  548. ): Promise<PaginatedPages> {
  549. const sortOpt = {};
  550. sortOpt[options.sort] = options.desc;
  551. const Page = this;
  552. const User = mongoose.model('User') as any;
  553. if (path == null) {
  554. throw new Error('path is required.');
  555. }
  556. const baseQuery = this.find({});
  557. const queryBuilder = new PageQueryBuilder(baseQuery, includeEmpty);
  558. if (!options.includeTrashed) {
  559. queryBuilder.addConditionToExcludeTrashed();
  560. }
  561. if (!options.includeWipPage) {
  562. queryBuilder.addConditionToExcludeWipPage();
  563. }
  564. queryBuilder.addConditionToListWithDescendants(path, options);
  565. queryBuilder.populateDataToList(User.USER_FIELDS_EXCEPT_CONFIDENTIAL);
  566. await queryBuilder.addViewerCondition(user);
  567. const pages = await Page.paginate(queryBuilder.query.clone(), {
  568. lean: true, sort: sortOpt, offset: options.offset, limit: options.limit,
  569. });
  570. const results = {
  571. pages: pages.docs, totalCount: pages.totalDocs, offset: options.offset, limit: options.limit,
  572. };
  573. return results;
  574. };
  575. /*
  576. * Find all ancestor pages by path. When duplicate pages found, it uses the oldest page as a result
  577. * The result will include the target as well
  578. */
  579. schema.statics.findTargetAndAncestorsByPathOrId = async function(pathOrId: string, user, userGroups): Promise<TargetAndAncestorsResult> {
  580. let path;
  581. if (!hasSlash(pathOrId)) {
  582. const _id = pathOrId;
  583. const page = await this.findOne({ _id });
  584. path = page == null ? '/' : page.path;
  585. }
  586. else {
  587. path = pathOrId;
  588. }
  589. const ancestorPaths = collectAncestorPaths(path);
  590. ancestorPaths.push(path); // include target
  591. // Do not populate
  592. const queryBuilder = new PageQueryBuilder(this.find(), true);
  593. await queryBuilder.addViewerCondition(user, userGroups);
  594. const _targetAndAncestors: PageDocument[] = await queryBuilder
  595. .addConditionAsOnTree()
  596. .addConditionToListByPathsArray(ancestorPaths)
  597. .addConditionToMinimizeDataForRendering()
  598. .addConditionToSortPagesByDescPath()
  599. .query
  600. .lean()
  601. .exec();
  602. // no same path pages
  603. const ancestorsMap = new Map<string, PageDocument>();
  604. _targetAndAncestors.forEach(page => ancestorsMap.set(page.path, page));
  605. const targetAndAncestors = Array.from(ancestorsMap.values());
  606. const rootPage = targetAndAncestors[targetAndAncestors.length - 1];
  607. return { targetAndAncestors, rootPage };
  608. };
  609. /**
  610. * Create empty pages at paths at which no pages exist
  611. * @param paths Page paths
  612. * @param aggrPipelineForExistingPages AggregationPipeline object to find existing pages at paths
  613. */
  614. schema.statics.createEmptyPagesByPaths = async function(paths: string[], aggrPipelineForExistingPages: any[]): Promise<void> {
  615. const existingPages = await this.aggregate(aggrPipelineForExistingPages);
  616. const existingPagePaths = existingPages.map(page => page.path);
  617. const notExistingPagePaths = paths.filter(path => !existingPagePaths.includes(path));
  618. await this.insertMany(notExistingPagePaths.map(path => ({ path, isEmpty: true })));
  619. };
  620. /**
  621. * Find a parent page by path
  622. */
  623. schema.statics.findParentByPath = async function(path: string): Promise<HydratedDocument<PageDocument> | null> {
  624. const parentPath = nodePath.dirname(path);
  625. const builder = new PageQueryBuilder(this.find({ path: parentPath }), true);
  626. const pagesCanBeParent = await builder
  627. .addConditionAsOnTree()
  628. .query
  629. .exec();
  630. if (pagesCanBeParent.length >= 1) {
  631. return pagesCanBeParent[0]; // the earliest page will be the result
  632. }
  633. return null;
  634. };
  635. /*
  636. * Utils from obsolete-page.js
  637. */
  638. export async function pushRevision(pageData, newRevision, user) {
  639. await newRevision.save();
  640. pageData.revision = newRevision;
  641. pageData.latestRevisionBodyLength = newRevision.body.length;
  642. pageData.lastUpdateUser = user?._id ?? user;
  643. pageData.updatedAt = Date.now();
  644. return pageData.save();
  645. }
  646. /**
  647. * add/subtract descendantCount of pages with provided paths by increment.
  648. * increment can be negative number
  649. */
  650. schema.statics.incrementDescendantCountOfPageIds = async function(pageIds: ObjectIdLike[], increment: number): Promise<void> {
  651. await this.updateMany({ _id: { $in: pageIds } }, { $inc: { descendantCount: increment } });
  652. };
  653. /**
  654. * recount descendantCount of a page with the provided id and return it
  655. */
  656. schema.statics.recountDescendantCount = async function(id: ObjectIdLike): Promise<number> {
  657. const res = await this.aggregate(
  658. [
  659. {
  660. $match: {
  661. parent: id,
  662. },
  663. },
  664. {
  665. $project: {
  666. parent: 1,
  667. isEmpty: 1,
  668. descendantCount: 1,
  669. },
  670. },
  671. {
  672. $group: {
  673. _id: '$parent',
  674. sumOfDescendantCount: {
  675. $sum: '$descendantCount',
  676. },
  677. sumOfDocsCount: {
  678. $sum: {
  679. $cond: { if: { $eq: ['$isEmpty', true] }, then: 0, else: 1 }, // exclude isEmpty true page from sumOfDocsCount
  680. },
  681. },
  682. },
  683. },
  684. {
  685. $set: {
  686. descendantCount: {
  687. $sum: ['$sumOfDescendantCount', '$sumOfDocsCount'],
  688. },
  689. },
  690. },
  691. ],
  692. );
  693. return res.length === 0 ? 0 : res[0].descendantCount;
  694. };
  695. schema.statics.findAncestorsUsingParentRecursively = async function(pageId: ObjectIdLike, shouldIncludeTarget: boolean) {
  696. const self = this;
  697. const target = await this.findById(pageId);
  698. if (target == null) {
  699. throw Error('Target not found');
  700. }
  701. async function findAncestorsRecursively(target, ancestors = shouldIncludeTarget ? [target] : []) {
  702. const parent = await self.findOne({ _id: target.parent });
  703. if (parent == null) {
  704. return ancestors;
  705. }
  706. return findAncestorsRecursively(parent, [...ancestors, parent]);
  707. }
  708. return findAncestorsRecursively(target);
  709. };
  710. // TODO: write test code
  711. /**
  712. * Recursively removes empty pages at leaf position.
  713. * @param pageId ObjectIdLike
  714. * @returns Promise<void>
  715. */
  716. schema.statics.removeLeafEmptyPagesRecursively = async function(pageId: ObjectIdLike): Promise<void> {
  717. const self = this;
  718. const initialPage = await this.findById(pageId);
  719. if (initialPage == null) {
  720. return;
  721. }
  722. if (!initialPage.isEmpty) {
  723. return;
  724. }
  725. async function generatePageIdsToRemove(childPage, page, pageIds: ObjectIdLike[] = []): Promise<ObjectIdLike[]> {
  726. if (!page.isEmpty) {
  727. return pageIds;
  728. }
  729. const isChildrenOtherThanTargetExist = await self.exists({ _id: { $ne: childPage?._id }, parent: page._id });
  730. if (isChildrenOtherThanTargetExist) {
  731. return pageIds;
  732. }
  733. pageIds.push(page._id);
  734. const nextPage = await self.findById(page.parent);
  735. if (nextPage == null) {
  736. return pageIds;
  737. }
  738. return generatePageIdsToRemove(page, nextPage, pageIds);
  739. }
  740. const pageIdsToRemove = await generatePageIdsToRemove(null, initialPage);
  741. await this.deleteMany({ _id: { $in: pageIdsToRemove } });
  742. };
  743. schema.statics.normalizeDescendantCountById = async function(pageId) {
  744. const children = await this.find({ parent: pageId });
  745. const sumChildrenDescendantCount = children.map(d => d.descendantCount).reduce((c1, c2) => c1 + c2);
  746. const sumChildPages = children.filter(p => !p.isEmpty).length;
  747. return this.updateOne({ _id: pageId }, { $set: { descendantCount: sumChildrenDescendantCount + sumChildPages } }, { new: true });
  748. };
  749. schema.statics.takeOffFromTree = async function(pageId: ObjectIdLike) {
  750. return this.findByIdAndUpdate(pageId, { $set: { parent: null } });
  751. };
  752. schema.statics.removeEmptyPages = async function(pageIdsToNotRemove: ObjectIdLike[], paths: string[]): Promise<void> {
  753. await this.deleteMany({
  754. _id: {
  755. $nin: pageIdsToNotRemove,
  756. },
  757. path: {
  758. $in: paths,
  759. },
  760. isEmpty: true,
  761. });
  762. };
  763. /**
  764. * Find a not empty parent recursively.
  765. * @param {string} path
  766. * @returns {Promise<PageDocument | null>}
  767. */
  768. schema.statics.findNotEmptyParentByPathRecursively = async function(path: string): Promise<PageDocument | null> {
  769. const parent = await this.findParentByPath(path);
  770. if (parent == null) {
  771. return null;
  772. }
  773. const recursive = async(page: PageDocument): Promise<PageDocument> => {
  774. if (!page.isEmpty) {
  775. return page;
  776. }
  777. const next = await this.findById(page.parent);
  778. if (next == null || isTopPage(next.path)) {
  779. return page;
  780. }
  781. return recursive(next);
  782. };
  783. const notEmptyParent = await recursive(parent);
  784. return notEmptyParent;
  785. };
  786. schema.statics.findParent = async function(pageId): Promise<PageDocument | null> {
  787. return this.findOne({ _id: pageId });
  788. };
  789. schema.statics.PageQueryBuilder = PageQueryBuilder as any; // mongoose does not support constructor type as statics attrs type
  790. export function generateGrantCondition(
  791. user, userGroups: ObjectIdLike[] | null, includeAnyoneWithTheLink = false, showPagesRestrictedByOwner = false, showPagesRestrictedByGroup = false,
  792. ): { $or: any[] } {
  793. const grantConditions: AnyObject[] = [
  794. { grant: null },
  795. { grant: GRANT_PUBLIC },
  796. ];
  797. if (includeAnyoneWithTheLink) {
  798. grantConditions.push({ grant: GRANT_RESTRICTED });
  799. }
  800. if (showPagesRestrictedByOwner) {
  801. grantConditions.push(
  802. { grant: GRANT_SPECIFIED },
  803. { grant: GRANT_OWNER },
  804. );
  805. }
  806. else if (user != null) {
  807. grantConditions.push(
  808. { grant: GRANT_SPECIFIED, grantedUsers: user._id },
  809. { grant: GRANT_OWNER, grantedUsers: user._id },
  810. );
  811. }
  812. if (showPagesRestrictedByGroup) {
  813. grantConditions.push(
  814. { grant: GRANT_USER_GROUP },
  815. );
  816. }
  817. else if (userGroups != null && userGroups.length > 0) {
  818. grantConditions.push(
  819. {
  820. grant: GRANT_USER_GROUP,
  821. grantedGroups: { $elemMatch: { item: { $in: userGroups } } },
  822. },
  823. );
  824. }
  825. return {
  826. $or: grantConditions,
  827. };
  828. }
  829. schema.statics.generateGrantCondition = generateGrantCondition;
  830. function generateGrantConditionForSystemDeletion(): { $or: any[] } {
  831. const grantCondition: AnyObject[] = [
  832. { grant: null },
  833. { grant: GRANT_PUBLIC },
  834. { grant: GRANT_RESTRICTED },
  835. { grant: GRANT_SPECIFIED },
  836. { grant: GRANT_OWNER },
  837. { grant: GRANT_USER_GROUP },
  838. ];
  839. return {
  840. $or: grantCondition,
  841. };
  842. }
  843. schema.statics.generateGrantConditionForSystemDeletion = generateGrantConditionForSystemDeletion;
  844. // find ancestor page with isEmpty: false. If parameter path is '/', return null
  845. schema.statics.findNonEmptyClosestAncestor = async function(path: string): Promise<PageDocument | null> {
  846. if (path === '/') {
  847. return null;
  848. }
  849. const builderForAncestors = new PageQueryBuilder(this.find(), false); // empty page not included
  850. const ancestors = await builderForAncestors
  851. .addConditionToListOnlyAncestors(path) // only ancestor paths
  852. .addConditionToSortPagesByDescPath() // sort by path in Desc. Long to Short.
  853. .query
  854. .exec();
  855. return ancestors[0] ?? null;
  856. };
  857. schema.statics.removeGroupsToDeleteFromPages = async function(pages: PageDocument[], groupsToDelete: UserGroupDocument[] | ExternalUserGroupDocument[]) {
  858. const groupsToDeleteIds = groupsToDelete.map(group => group._id.toString());
  859. const pageGroups = pages.reduce((acc: { canPublicize: PageDocument[], cannotPublicize: PageDocument[] }, page) => {
  860. const canPublicize = page.grantedGroups.every(group => groupsToDeleteIds.includes(getIdForRef(group.item).toString()));
  861. acc[canPublicize ? 'canPublicize' : 'cannotPublicize'].push(page);
  862. return acc;
  863. }, { canPublicize: [], cannotPublicize: [] });
  864. // Only publicize pages that can only be accessed by the groups to be deleted
  865. const publicizeQueries = pageGroups.canPublicize.map((page) => {
  866. return {
  867. updateOne: {
  868. filter: { _id: page._id },
  869. update: {
  870. grantedGroups: [],
  871. grant: this.GRANT_PUBLIC,
  872. },
  873. },
  874. };
  875. });
  876. // Remove the groups to be deleted from the grantedGroups of the pages that can be accessed by other groups
  877. const removeFromGrantedGroupsQueries = pageGroups.cannotPublicize.map((page) => {
  878. return {
  879. updateOne: {
  880. filter: { _id: page._id },
  881. update: { $set: { grantedGroups: page.grantedGroups.filter(group => !groupsToDeleteIds.includes(getIdForRef(group.item).toString())) } },
  882. },
  883. };
  884. });
  885. await this.bulkWrite([...publicizeQueries, ...removeFromGrantedGroupsQueries]);
  886. };
  887. /*
  888. * get latest revision body length
  889. */
  890. schema.methods.getLatestRevisionBodyLength = async function(this: PageDocument): Promise<number | null | undefined> {
  891. if (!this.isLatestRevision() || this.revision == null) {
  892. return null;
  893. }
  894. if (this.latestRevisionBodyLength == null) {
  895. await this.calculateAndUpdateLatestRevisionBodyLength();
  896. }
  897. return this.latestRevisionBodyLength;
  898. };
  899. /*
  900. * calculate and update latestRevisionBodyLength
  901. */
  902. schema.methods.calculateAndUpdateLatestRevisionBodyLength = async function(this: PageDocument): Promise<void> {
  903. if (!this.isLatestRevision() || this.revision == null) {
  904. logger.error('revision field is required.');
  905. return;
  906. }
  907. // eslint-disable-next-line rulesdir/no-populate
  908. const populatedPageDocument = await this.populate<PageDocument>('revision', 'body');
  909. assert(populatedPageDocument.revision != null);
  910. assert(isPopulated(populatedPageDocument.revision));
  911. this.latestRevisionBodyLength = populatedPageDocument.revision.body.length;
  912. await this.save();
  913. };
  914. schema.methods.publish = function() {
  915. this.wip = undefined;
  916. this.ttlTimestamp = undefined;
  917. };
  918. schema.methods.unpublish = function() {
  919. this.wip = true;
  920. this.ttlTimestamp = undefined;
  921. };
  922. schema.methods.makeWip = function(disableTtl: boolean) {
  923. this.wip = true;
  924. if (!disableTtl) {
  925. this.ttlTimestamp = new Date();
  926. }
  927. };
  928. /*
  929. * Merge obsolete page model methods and define new methods which depend on crowi instance
  930. */
  931. export default function PageModel(crowi): any {
  932. // add old page schema methods
  933. const pageSchema = getPageSchema(crowi);
  934. schema.methods = { ...pageSchema.methods, ...schema.methods };
  935. schema.statics = { ...pageSchema.statics, ...schema.statics };
  936. return getOrCreateModel<PageDocument, PageModel>('Page', schema as any); // TODO: improve type
  937. }