page.ts 33 KB

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