page.ts 37 KB

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