page.ts 37 KB

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