obsolete-page.js 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837
  1. import { GroupType, Origin } from '@growi/core';
  2. import {
  3. pagePathUtils,
  4. pathUtils,
  5. templateChecker,
  6. } from '@growi/core/dist/utils';
  7. import { differenceInYears } from 'date-fns/differenceInYears';
  8. import escapeStringRegexp from 'escape-string-regexp';
  9. import { Comment } from '~/features/comment/server/models/comment';
  10. import ExternalUserGroup from '~/features/external-user-group/server/models/external-user-group';
  11. import ExternalUserGroupRelation from '~/features/external-user-group/server/models/external-user-group-relation';
  12. import loggerFactory from '~/utils/logger';
  13. import { configManager } from '../service/config-manager';
  14. import UserGroup from './user-group';
  15. import UserGroupRelation from './user-group-relation';
  16. const logger = loggerFactory('growi:models:page');
  17. // disable no-return-await for model functions
  18. /* eslint-disable no-return-await */
  19. /* eslint-disable no-use-before-define */
  20. const nodePath = require('path');
  21. const mongoose = require('mongoose');
  22. const urljoin = require('url-join');
  23. const { isTopPage, isTrashPage } = pagePathUtils;
  24. const { checkTemplatePath } = templateChecker;
  25. const GRANT_PUBLIC = 1;
  26. const GRANT_RESTRICTED = 2;
  27. const GRANT_SPECIFIED = 3;
  28. const GRANT_OWNER = 4;
  29. const GRANT_USER_GROUP = 5;
  30. const PAGE_GRANT_ERROR = 1;
  31. const STATUS_PUBLISHED = 'published';
  32. const STATUS_DELETED = 'deleted';
  33. // schema definition has moved to page.ts
  34. const pageSchema = {
  35. statics: {},
  36. methods: {},
  37. };
  38. /**
  39. * return an array of ancestors paths that is extracted from specified pagePath
  40. * e.g.
  41. * when `pagePath` is `/foo/bar/baz`,
  42. * this method returns [`/foo/bar/baz`, `/foo/bar`, `/foo`, `/`]
  43. *
  44. * @param {string} pagePath
  45. * @return {string[]} ancestors paths
  46. */
  47. export const extractToAncestorsPaths = (pagePath) => {
  48. const ancestorsPaths = [];
  49. let parentPath;
  50. while (parentPath !== '/') {
  51. parentPath = nodePath.dirname(parentPath || pagePath);
  52. ancestorsPaths.push(parentPath);
  53. }
  54. return ancestorsPaths;
  55. };
  56. /**
  57. * populate page (Query or Document) to show revision
  58. * @param {any} page Query or Document
  59. * @param {string} userPublicFields string to set to select
  60. * @param {boolean} shouldExcludeBody boolean indicating whether to include 'revision.body' or not
  61. */
  62. /* eslint-disable object-curly-newline, object-property-newline */
  63. export const populateDataToShowRevision = (
  64. page,
  65. userPublicFields,
  66. shouldExcludeBody = false,
  67. ) => {
  68. return page.populate([
  69. { path: 'lastUpdateUser', select: userPublicFields },
  70. { path: 'creator', select: userPublicFields },
  71. { path: 'deleteUser', select: userPublicFields },
  72. { path: 'grantedGroups.item' },
  73. {
  74. path: 'revision',
  75. select: shouldExcludeBody ? '-body' : undefined,
  76. populate: {
  77. path: 'author',
  78. select: userPublicFields,
  79. },
  80. },
  81. ]);
  82. };
  83. /* eslint-enable object-curly-newline, object-property-newline */
  84. /** @param {import('~/server/crowi').default | null} crowi Crowi instance */
  85. export const getPageSchema = (crowi) => {
  86. let pageEvent;
  87. // init event
  88. if (crowi != null) {
  89. pageEvent = crowi.event('page');
  90. pageEvent.on('create', pageEvent.onCreate);
  91. pageEvent.on('update', pageEvent.onUpdate);
  92. pageEvent.on('createMany', pageEvent.onCreateMany);
  93. pageEvent.on('addSeenUsers', pageEvent.onAddSeenUsers);
  94. }
  95. function validateCrowi() {
  96. if (crowi == null) {
  97. throw new Error(
  98. '"crowi" is null. Init User model with "crowi" argument first.',
  99. );
  100. }
  101. }
  102. pageSchema.methods.isDeleted = function () {
  103. return isTrashPage(this.path);
  104. };
  105. pageSchema.methods.isPublic = function () {
  106. if (!this.grant || this.grant === GRANT_PUBLIC) {
  107. return true;
  108. }
  109. return false;
  110. };
  111. pageSchema.methods.isTopPage = function () {
  112. return isTopPage(this.path);
  113. };
  114. pageSchema.methods.isTemplate = function () {
  115. return checkTemplatePath(this.path);
  116. };
  117. pageSchema.methods.isLatestRevision = function () {
  118. // populate されていなくて判断できない
  119. if (!this.latestRevision || !this.revision) {
  120. return true;
  121. }
  122. // comparing ObjectId with string
  123. // biome-ignore lint/suspicious/noDoubleEquals: ignore
  124. return this.latestRevision == this.revision._id.toString();
  125. };
  126. pageSchema.methods.findRelatedTagsById = async function () {
  127. const PageTagRelation = mongoose.model('PageTagRelation');
  128. const relations = await PageTagRelation.find({
  129. relatedPage: this._id,
  130. }).populate('relatedTag');
  131. return relations.map((relation) => {
  132. return relation.relatedTag.name;
  133. });
  134. };
  135. pageSchema.methods.isUpdatable = async function (previousRevision, origin) {
  136. const populatedPageDataWithRevisionOrigin = await this.populate(
  137. 'revision',
  138. 'origin',
  139. );
  140. const latestRevisionOrigin =
  141. populatedPageDataWithRevisionOrigin.revision.origin;
  142. const ignoreLatestRevision =
  143. origin === Origin.Editor &&
  144. (latestRevisionOrigin === Origin.Editor ||
  145. latestRevisionOrigin === Origin.View);
  146. if (ignoreLatestRevision) {
  147. return true;
  148. }
  149. const revision = this.latestRevision || this.revision._id;
  150. // comparing ObjectId with string
  151. // biome-ignore lint/suspicious/noDoubleEquals: ignore
  152. if (revision != previousRevision) {
  153. return false;
  154. }
  155. return true;
  156. };
  157. pageSchema.methods.isLiked = function (user) {
  158. if (user == null || user._id == null) {
  159. return false;
  160. }
  161. return this.liker.some((likedUserId) => {
  162. return likedUserId.toString() === user._id.toString();
  163. });
  164. };
  165. pageSchema.methods.like = function (userData) {
  166. return new Promise((resolve, reject) => {
  167. const added = this.liker.addToSet(userData._id);
  168. if (added.length > 0) {
  169. this.save((err, data) => {
  170. if (err) {
  171. return reject(err);
  172. }
  173. logger.debug('liker updated!', added);
  174. return resolve(data);
  175. });
  176. } else {
  177. logger.debug('liker not updated');
  178. return reject(new Error('Already liked'));
  179. }
  180. });
  181. };
  182. pageSchema.methods.unlike = function (userData, callback) {
  183. return new Promise((resolve, reject) => {
  184. const beforeCount = this.liker.length;
  185. this.liker.pull(userData._id);
  186. if (this.liker.length !== beforeCount) {
  187. this.save((err, data) => {
  188. if (err) {
  189. return reject(err);
  190. }
  191. return resolve(data);
  192. });
  193. } else {
  194. logger.debug('liker not updated');
  195. return reject(new Error('Already unliked'));
  196. }
  197. });
  198. };
  199. pageSchema.methods.isSeenUser = function (userData) {
  200. return this.seenUsers.includes(userData._id);
  201. };
  202. pageSchema.methods.seen = async function (userData) {
  203. if (this.isSeenUser(userData)) {
  204. logger.debug('seenUsers not updated');
  205. return this;
  206. }
  207. if (!userData || !userData._id) {
  208. throw new Error('User data is not valid');
  209. }
  210. const added = this.seenUsers.addToSet(userData._id);
  211. const saved = await this.save();
  212. logger.debug('seenUsers updated!', added);
  213. pageEvent.emit('addSeenUsers', saved);
  214. return saved;
  215. };
  216. pageSchema.methods.updateSlackChannels = function (slackChannels) {
  217. this.slackChannels = slackChannels;
  218. return this.save();
  219. };
  220. pageSchema.methods.initLatestRevisionField = async function (revisionId) {
  221. this.latestRevision = this.revision;
  222. if (revisionId != null) {
  223. this.revision = revisionId;
  224. }
  225. };
  226. pageSchema.methods.populateDataToShowRevision = async function (
  227. shouldExcludeBody,
  228. ) {
  229. validateCrowi();
  230. const User = crowi.model('User');
  231. return populateDataToShowRevision(
  232. this,
  233. User.USER_FIELDS_EXCEPT_CONFIDENTIAL,
  234. shouldExcludeBody,
  235. );
  236. };
  237. pageSchema.methods.populateDataToMakePresentation = async function (
  238. revisionId,
  239. ) {
  240. this.latestRevision = this.revision;
  241. if (revisionId != null) {
  242. this.revision = revisionId;
  243. }
  244. return this.populate('revision');
  245. };
  246. pageSchema.methods.applyScope = function (user, grant, grantUserGroupIds) {
  247. // Reset
  248. this.grantedUsers = [];
  249. this.grantedGroups = [];
  250. this.grant = grant || GRANT_PUBLIC;
  251. if (grant === GRANT_OWNER) {
  252. this.grantedUsers.push(user?._id ?? user);
  253. }
  254. if (grant === GRANT_USER_GROUP) {
  255. this.grantedGroups = grantUserGroupIds;
  256. }
  257. };
  258. pageSchema.methods.getContentAge = function () {
  259. return differenceInYears(new Date(), this.updatedAt);
  260. };
  261. pageSchema.statics.updateCommentCount = function (pageId) {
  262. validateCrowi();
  263. return Comment.countCommentByPageId(pageId).then((count) => {
  264. this.update({ _id: pageId }, { commentCount: count }, {}, (err, data) => {
  265. if (err) {
  266. logger.debug('Update commentCount Error', err);
  267. throw err;
  268. }
  269. return data;
  270. });
  271. });
  272. };
  273. pageSchema.statics.getDeletedPageName = (path) => {
  274. if (path.match('/')) {
  275. // eslint-disable-next-line no-param-reassign
  276. path = path.substr(1);
  277. }
  278. return `/trash/${path}`;
  279. };
  280. pageSchema.statics.getRevertDeletedPageName = (path) =>
  281. path.replace('/trash', '');
  282. pageSchema.statics.fixToCreatableName = (path) => path.replace(/\/\//g, '/');
  283. pageSchema.statics.updateRevision = function (pageId, revisionId, cb) {
  284. this.update({ _id: pageId }, { revision: revisionId }, {}, (err, data) => {
  285. cb(err, data);
  286. });
  287. };
  288. /**
  289. * return whether the user is accessible to the page
  290. * @param {string} id ObjectId
  291. * @param {User} user
  292. */
  293. pageSchema.statics.isAccessiblePageByViewer = async function (id, user) {
  294. const baseQuery = this.count({ _id: id });
  295. const userGroups =
  296. user != null
  297. ? [
  298. ...(await UserGroupRelation.findAllUserGroupIdsRelatedToUser(user)),
  299. ...(await ExternalUserGroupRelation.findAllUserGroupIdsRelatedToUser(
  300. user,
  301. )),
  302. ]
  303. : [];
  304. const queryBuilder = new this.PageQueryBuilder(baseQuery);
  305. queryBuilder.addConditionToFilteringByViewer(user, userGroups, true);
  306. const count = await queryBuilder.query.exec();
  307. return count > 0;
  308. };
  309. /**
  310. * @param {string} id ObjectId
  311. * @param {User} user User instance
  312. * @param {UserGroup[]} userGroups List of UserGroup instances
  313. */
  314. pageSchema.statics.findByIdAndViewer = async function (
  315. id,
  316. user,
  317. userGroups,
  318. includeEmpty = false,
  319. ) {
  320. const baseQuery = this.findOne({ _id: id });
  321. const relatedUserGroups =
  322. user != null && userGroups == null
  323. ? [
  324. ...(await UserGroupRelation.findAllUserGroupIdsRelatedToUser(user)),
  325. ...(await ExternalUserGroupRelation.findAllUserGroupIdsRelatedToUser(
  326. user,
  327. )),
  328. ]
  329. : userGroups;
  330. const queryBuilder = new this.PageQueryBuilder(baseQuery, includeEmpty);
  331. queryBuilder.addConditionToFilteringByViewer(user, relatedUserGroups, true);
  332. return queryBuilder.query.exec();
  333. };
  334. // find page by path
  335. pageSchema.statics.findByPath = function (path, includeEmpty = false) {
  336. if (path == null) {
  337. return null;
  338. }
  339. const builder = new this.PageQueryBuilder(
  340. this.findOne({ path }),
  341. includeEmpty,
  342. );
  343. return builder.query.exec();
  344. };
  345. /**
  346. * @param {string} path Page path
  347. * @param {User} user User instance
  348. * @param {UserGroup[]} userGroups List of UserGroup instances
  349. */
  350. pageSchema.statics.findAncestorByPathAndViewer = async function (
  351. path,
  352. user,
  353. userGroups,
  354. includeEmpty = false,
  355. ) {
  356. if (path == null) {
  357. throw new Error('path is required.');
  358. }
  359. if (path === '/') {
  360. return null;
  361. }
  362. const ancestorsPaths = extractToAncestorsPaths(path);
  363. // pick the longest one
  364. const baseQuery = this.findOne({ path: { $in: ancestorsPaths } }).sort({
  365. path: -1,
  366. });
  367. const relatedUserGroups =
  368. user != null && userGroups == null
  369. ? [
  370. ...(await UserGroupRelation.findAllUserGroupIdsRelatedToUser(user)),
  371. ...(await ExternalUserGroupRelation.findAllUserGroupIdsRelatedToUser(
  372. user,
  373. )),
  374. ]
  375. : userGroups;
  376. const queryBuilder = new this.PageQueryBuilder(baseQuery, includeEmpty);
  377. queryBuilder.addConditionToFilteringByViewer(user, relatedUserGroups);
  378. return queryBuilder.query.exec();
  379. };
  380. /**
  381. * find pages that is match with `path` and its descendants
  382. */
  383. pageSchema.statics.findListWithDescendants = async function (
  384. path,
  385. user,
  386. option = {},
  387. includeEmpty = false,
  388. ) {
  389. const builder = new this.PageQueryBuilder(this.find(), includeEmpty);
  390. builder.addConditionToListWithDescendants(path, option);
  391. return findListFromBuilderAndViewer(builder, user, false, option);
  392. };
  393. /**
  394. * find pages that is match with `path` and its descendants which user is able to manage
  395. */
  396. pageSchema.statics.findManageableListWithDescendants = async function (
  397. page,
  398. user,
  399. option = {},
  400. includeEmpty = false,
  401. ) {
  402. if (user == null) {
  403. return null;
  404. }
  405. const builder = new this.PageQueryBuilder(this.find(), includeEmpty);
  406. builder.addConditionToListWithDescendants(page.path, option);
  407. // add grant conditions
  408. await addConditionToFilteringByViewerToEdit(builder, user);
  409. const { pages } = await findListFromBuilderAndViewer(
  410. builder,
  411. user,
  412. false,
  413. option,
  414. );
  415. // add page if 'grant' is GRANT_RESTRICTED
  416. // because addConditionToListWithDescendants excludes GRANT_RESTRICTED pages
  417. if (page.grant === GRANT_RESTRICTED) {
  418. pages.push(page);
  419. }
  420. return pages;
  421. };
  422. /**
  423. * find pages that start with `path`
  424. */
  425. pageSchema.statics.findListByStartWith = async function (
  426. path,
  427. user,
  428. option,
  429. includeEmpty = false,
  430. ) {
  431. const builder = new this.PageQueryBuilder(this.find(), includeEmpty);
  432. builder.addConditionToListByStartWith(path, option);
  433. return findListFromBuilderAndViewer(builder, user, false, option);
  434. };
  435. /**
  436. * find pages that is created by targetUser
  437. *
  438. * @param {User} targetUser
  439. * @param {User} currentUser
  440. * @param {any} option
  441. */
  442. pageSchema.statics.findListByCreator = async function (
  443. targetUser,
  444. currentUser,
  445. option,
  446. ) {
  447. const opt = Object.assign({ sort: 'createdAt', desc: -1 }, option);
  448. const builder = new this.PageQueryBuilder(
  449. this.find({ creator: targetUser._id }),
  450. );
  451. let showAnyoneKnowsLink = null;
  452. if (targetUser != null && currentUser != null) {
  453. showAnyoneKnowsLink = targetUser._id.equals(currentUser._id);
  454. }
  455. return await findListFromBuilderAndViewer(
  456. builder,
  457. currentUser,
  458. showAnyoneKnowsLink,
  459. opt,
  460. );
  461. };
  462. /**
  463. * find pages by PageQueryBuilder
  464. * @param {PageQueryBuilder} builder
  465. * @param {User} user
  466. * @param {boolean} showAnyoneKnowsLink
  467. * @param {any} option
  468. */
  469. async function findListFromBuilderAndViewer(
  470. builder,
  471. user,
  472. showAnyoneKnowsLink,
  473. option,
  474. ) {
  475. validateCrowi();
  476. const User = crowi.model('User');
  477. const opt = Object.assign({ sort: 'updatedAt', desc: -1 }, option);
  478. const sortOpt = {};
  479. sortOpt[opt.sort] = opt.desc;
  480. // exclude trashed pages
  481. if (!opt.includeTrashed) {
  482. builder.addConditionToExcludeTrashed();
  483. }
  484. // add grant conditions
  485. await addConditionToFilteringByViewerForList(
  486. builder,
  487. user,
  488. showAnyoneKnowsLink,
  489. );
  490. // count
  491. const totalCount = await builder.query.exec('count');
  492. // find
  493. builder.addConditionToPagenate(opt.offset, opt.limit, sortOpt);
  494. builder.populateDataToList(User.USER_FIELDS_EXCEPT_CONFIDENTIAL);
  495. const pages = await builder.query.lean().clone().exec('find');
  496. const result = {
  497. pages,
  498. totalCount,
  499. offset: opt.offset,
  500. limit: opt.limit,
  501. };
  502. return result;
  503. }
  504. /**
  505. * Add condition that filter pages by viewer
  506. * by considering Config
  507. *
  508. * @param {PageQueryBuilder} builder
  509. * @param {User} user
  510. * @param {boolean} showAnyoneKnowsLink
  511. */
  512. async function addConditionToFilteringByViewerForList(
  513. builder,
  514. user,
  515. showAnyoneKnowsLink,
  516. ) {
  517. validateCrowi();
  518. // determine User condition
  519. const hidePagesRestrictedByOwner = configManager.getConfig(
  520. 'security:list-policy:hideRestrictedByOwner',
  521. );
  522. const hidePagesRestrictedByGroup = configManager.getConfig(
  523. 'security:list-policy:hideRestrictedByGroup',
  524. );
  525. // determine UserGroup condition
  526. const userGroups =
  527. user != null
  528. ? [
  529. ...(await UserGroupRelation.findAllUserGroupIdsRelatedToUser(user)),
  530. ...(await ExternalUserGroupRelation.findAllUserGroupIdsRelatedToUser(
  531. user,
  532. )),
  533. ]
  534. : null;
  535. return builder.addConditionToFilteringByViewer(
  536. user,
  537. userGroups,
  538. showAnyoneKnowsLink,
  539. !hidePagesRestrictedByOwner,
  540. !hidePagesRestrictedByGroup,
  541. );
  542. }
  543. /**
  544. * Add condition that filter pages by viewer
  545. * by considering Config
  546. *
  547. * @param {PageQueryBuilder} builder
  548. * @param {User} user
  549. * @param {boolean} showAnyoneKnowsLink
  550. */
  551. async function addConditionToFilteringByViewerToEdit(builder, user) {
  552. // determine UserGroup condition
  553. const userGroups =
  554. user != null
  555. ? [
  556. ...(await UserGroupRelation.findAllUserGroupIdsRelatedToUser(user)),
  557. ...(await ExternalUserGroupRelation.findAllUserGroupIdsRelatedToUser(
  558. user,
  559. )),
  560. ]
  561. : null;
  562. return builder.addConditionToFilteringByViewer(
  563. user,
  564. userGroups,
  565. false,
  566. false,
  567. false,
  568. );
  569. }
  570. /**
  571. * export addConditionToFilteringByViewerForList as static method
  572. */
  573. pageSchema.statics.addConditionToFilteringByViewerForList =
  574. addConditionToFilteringByViewerForList;
  575. /**
  576. * export addConditionToFilteringByViewerToEdit as static method
  577. */
  578. pageSchema.statics.addConditionToFilteringByViewerToEdit =
  579. addConditionToFilteringByViewerToEdit;
  580. /**
  581. * Throw error for growi-lsx-plugin (v1.x)
  582. */
  583. pageSchema.statics.generateQueryToListByStartWith = function (
  584. path,
  585. user,
  586. option,
  587. ) {
  588. const dummyQuery = this.find();
  589. dummyQuery.exec = async () => {
  590. throw new Error(
  591. 'Plugin version mismatch. Upgrade growi-lsx-plugin to v2.0.0 or above.',
  592. );
  593. };
  594. return dummyQuery;
  595. };
  596. pageSchema.statics.generateQueryToListWithDescendants =
  597. pageSchema.statics.generateQueryToListByStartWith;
  598. /**
  599. * find all templates applicable to the new page
  600. */
  601. pageSchema.statics.findTemplate = async function (path) {
  602. const templatePath = nodePath.posix.dirname(path);
  603. const pathList = generatePathsOnTree(path, []);
  604. const regexpList = pathList.map((path) => {
  605. const pathWithTrailingSlash = pathUtils.addTrailingSlash(path);
  606. return new RegExp(
  607. `^${escapeStringRegexp(pathWithTrailingSlash)}_{1,2}template$`,
  608. );
  609. });
  610. const templatePages = await this.find({ path: { $in: regexpList } })
  611. .populate({ path: 'revision', model: 'Revision' })
  612. .exec();
  613. return fetchTemplate(templatePages, templatePath);
  614. };
  615. const generatePathsOnTree = (path, pathList) => {
  616. pathList.push(path);
  617. if (path === '/') {
  618. return pathList;
  619. }
  620. const newPath = nodePath.posix.dirname(path);
  621. return generatePathsOnTree(newPath, pathList);
  622. };
  623. const assignTemplateByType = (templates, path, type) => {
  624. const targetTemplatePath = urljoin(path, `${type}template`);
  625. return templates.find((template) => {
  626. return template.path === targetTemplatePath;
  627. });
  628. };
  629. const assignDecendantsTemplate = (decendantsTemplates, path) => {
  630. const decendantsTemplate = assignTemplateByType(
  631. decendantsTemplates,
  632. path,
  633. '__',
  634. );
  635. if (decendantsTemplate) {
  636. return decendantsTemplate;
  637. }
  638. if (path === '/') {
  639. return;
  640. }
  641. const newPath = nodePath.posix.dirname(path);
  642. return assignDecendantsTemplate(decendantsTemplates, newPath);
  643. };
  644. const fetchTemplate = async (templates, templatePath) => {
  645. let templateBody;
  646. let templateTags;
  647. /**
  648. * get children template
  649. * __tempate: applicable only to immediate decendants
  650. */
  651. const childrenTemplate = assignTemplateByType(templates, templatePath, '_');
  652. /**
  653. * get decendants templates
  654. * _tempate: applicable to all pages under
  655. */
  656. const decendantsTemplate = assignDecendantsTemplate(
  657. templates,
  658. templatePath,
  659. );
  660. if (childrenTemplate) {
  661. templateBody = childrenTemplate.revision.body;
  662. templateTags = await childrenTemplate.findRelatedTagsById();
  663. } else if (decendantsTemplate) {
  664. templateBody = decendantsTemplate.revision.body;
  665. templateTags = await decendantsTemplate.findRelatedTagsById();
  666. }
  667. return { templateBody, templateTags };
  668. };
  669. pageSchema.statics.findListByPathsArray = async function (
  670. paths,
  671. includeEmpty = false,
  672. ) {
  673. const queryBuilder = new this.PageQueryBuilder(this.find(), includeEmpty);
  674. queryBuilder.addConditionToListByPathsArray(paths);
  675. return await queryBuilder.query.exec();
  676. };
  677. /**
  678. * transfer pages grant to specified user group
  679. * @param {Page[]} pages
  680. * @param {IGrantedGroup} transferToUserGroup
  681. */
  682. pageSchema.statics.transferPagesToGroup = async function (
  683. pages,
  684. transferToUserGroup,
  685. ) {
  686. const userGroupModel =
  687. transferToUserGroup.type === GroupType.userGroup
  688. ? UserGroup
  689. : ExternalUserGroup;
  690. if ((await userGroupModel.count({ _id: transferToUserGroup.item })) === 0) {
  691. throw Error(
  692. 'Cannot find the group to which private pages belong to. _id: ',
  693. transferToUserGroup.item,
  694. );
  695. }
  696. await this.updateMany(
  697. { _id: { $in: pages.map((p) => p._id) } },
  698. { grantedGroups: [transferToUserGroup] },
  699. );
  700. };
  701. pageSchema.statics.getHistories = () => {
  702. // TODO
  703. };
  704. pageSchema.statics.STATUS_PUBLISHED = STATUS_PUBLISHED;
  705. pageSchema.statics.STATUS_DELETED = STATUS_DELETED;
  706. pageSchema.statics.GRANT_PUBLIC = GRANT_PUBLIC;
  707. pageSchema.statics.GRANT_RESTRICTED = GRANT_RESTRICTED;
  708. pageSchema.statics.GRANT_SPECIFIED = GRANT_SPECIFIED;
  709. pageSchema.statics.GRANT_OWNER = GRANT_OWNER;
  710. pageSchema.statics.GRANT_USER_GROUP = GRANT_USER_GROUP;
  711. pageSchema.statics.PAGE_GRANT_ERROR = PAGE_GRANT_ERROR;
  712. return pageSchema;
  713. };