obsolete-page.js 28 KB

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