obsolete-page.js 22 KB

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