obsolete-page.js 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909
  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. // find page by path
  300. pageSchema.statics.findByPath = function(path, includeEmpty = false) {
  301. if (path == null) {
  302. return null;
  303. }
  304. const builder = new this.PageQueryBuilder(this.findOne({ path }), includeEmpty);
  305. return builder.query.exec();
  306. };
  307. /**
  308. * @param {string} path Page path
  309. * @param {User} user User instance
  310. * @param {UserGroup[]} userGroups List of UserGroup instances
  311. */
  312. pageSchema.statics.findAncestorByPathAndViewer = async function(path, user, userGroups, includeEmpty = false) {
  313. if (path == null) {
  314. throw new Error('path is required.');
  315. }
  316. if (path === '/') {
  317. return null;
  318. }
  319. const ancestorsPaths = extractToAncestorsPaths(path);
  320. // pick the longest one
  321. const baseQuery = this.findOne({ path: { $in: ancestorsPaths } }).sort({ path: -1 });
  322. let relatedUserGroups = userGroups;
  323. if (user != null && relatedUserGroups == null) {
  324. validateCrowi();
  325. const UserGroupRelation = crowi.model('UserGroupRelation');
  326. relatedUserGroups = await UserGroupRelation.findAllUserGroupIdsRelatedToUser(user);
  327. }
  328. const queryBuilder = new this.PageQueryBuilder(baseQuery, includeEmpty);
  329. queryBuilder.addConditionToFilteringByViewer(user, relatedUserGroups);
  330. return queryBuilder.query.exec();
  331. };
  332. /**
  333. * find pages that is match with `path` and its descendants
  334. */
  335. pageSchema.statics.findListWithDescendants = async function(path, user, option = {}, includeEmpty = false) {
  336. const builder = new this.PageQueryBuilder(this.find(), includeEmpty);
  337. builder.addConditionToListWithDescendants(path, option);
  338. return findListFromBuilderAndViewer(builder, user, false, option);
  339. };
  340. /**
  341. * find pages that is match with `path` and its descendants whitch user is able to manage
  342. */
  343. pageSchema.statics.findManageableListWithDescendants = async function(page, user, option = {}, includeEmpty = false) {
  344. if (user == null) {
  345. return null;
  346. }
  347. const builder = new this.PageQueryBuilder(this.find(), includeEmpty);
  348. builder.addConditionToListWithDescendants(page.path, option);
  349. // add grant conditions
  350. await addConditionToFilteringByViewerToEdit(builder, user);
  351. const { pages } = await findListFromBuilderAndViewer(builder, user, false, option);
  352. // add page if 'grant' is GRANT_RESTRICTED
  353. // because addConditionToListWithDescendants excludes GRANT_RESTRICTED pages
  354. if (page.grant === GRANT_RESTRICTED) {
  355. pages.push(page);
  356. }
  357. return pages;
  358. };
  359. /**
  360. * find pages that start with `path`
  361. */
  362. pageSchema.statics.findListByStartWith = async function(path, user, option, includeEmpty = false) {
  363. const builder = new this.PageQueryBuilder(this.find(), includeEmpty);
  364. builder.addConditionToListByStartWith(path, option);
  365. return findListFromBuilderAndViewer(builder, user, false, option);
  366. };
  367. /**
  368. * find pages that is created by targetUser
  369. *
  370. * @param {User} targetUser
  371. * @param {User} currentUser
  372. * @param {any} option
  373. */
  374. pageSchema.statics.findListByCreator = async function(targetUser, currentUser, option) {
  375. const opt = Object.assign({ sort: 'createdAt', desc: -1 }, option);
  376. const builder = new this.PageQueryBuilder(this.find({ creator: targetUser._id }));
  377. let showAnyoneKnowsLink = null;
  378. if (targetUser != null && currentUser != null) {
  379. showAnyoneKnowsLink = targetUser._id.equals(currentUser._id);
  380. }
  381. return await findListFromBuilderAndViewer(builder, currentUser, showAnyoneKnowsLink, opt);
  382. };
  383. pageSchema.statics.findListByPageIds = async function(ids, option = {}, shouldIncludeEmpty = false) {
  384. const User = crowi.model('User');
  385. const opt = Object.assign({}, option);
  386. const builder = new this.PageQueryBuilder(this.find({ _id: { $in: ids } }), shouldIncludeEmpty);
  387. builder.addConditionToPagenate(opt.offset, opt.limit);
  388. // count
  389. const totalCount = await builder.query.exec('count');
  390. // find
  391. builder.populateDataToList(User.USER_FIELDS_EXCEPT_CONFIDENTIAL);
  392. const pages = await builder.query.clone().exec('find');
  393. const result = {
  394. pages, totalCount, offset: opt.offset, limit: opt.limit,
  395. };
  396. return result;
  397. };
  398. /**
  399. * find pages by PageQueryBuilder
  400. * @param {PageQueryBuilder} builder
  401. * @param {User} user
  402. * @param {boolean} showAnyoneKnowsLink
  403. * @param {any} option
  404. */
  405. async function findListFromBuilderAndViewer(builder, user, showAnyoneKnowsLink, option) {
  406. validateCrowi();
  407. const User = crowi.model('User');
  408. const opt = Object.assign({ sort: 'updatedAt', desc: -1 }, option);
  409. const sortOpt = {};
  410. sortOpt[opt.sort] = opt.desc;
  411. // exclude trashed pages
  412. if (!opt.includeTrashed) {
  413. builder.addConditionToExcludeTrashed();
  414. }
  415. // add grant conditions
  416. await addConditionToFilteringByViewerForList(builder, user, showAnyoneKnowsLink);
  417. // count
  418. const totalCount = await builder.query.exec('count');
  419. // find
  420. builder.addConditionToPagenate(opt.offset, opt.limit, sortOpt);
  421. builder.populateDataToList(User.USER_FIELDS_EXCEPT_CONFIDENTIAL);
  422. const pages = await builder.query.lean().clone().exec('find');
  423. const result = {
  424. pages, totalCount, offset: opt.offset, limit: opt.limit,
  425. };
  426. return result;
  427. }
  428. /**
  429. * Add condition that filter pages by viewer
  430. * by considering Config
  431. *
  432. * @param {PageQueryBuilder} builder
  433. * @param {User} user
  434. * @param {boolean} showAnyoneKnowsLink
  435. */
  436. async function addConditionToFilteringByViewerForList(builder, user, showAnyoneKnowsLink) {
  437. validateCrowi();
  438. // determine User condition
  439. const hidePagesRestrictedByOwner = crowi.configManager.getConfig('crowi', 'security:list-policy:hideRestrictedByOwner');
  440. const hidePagesRestrictedByGroup = crowi.configManager.getConfig('crowi', 'security:list-policy:hideRestrictedByGroup');
  441. // determine UserGroup condition
  442. let userGroups = null;
  443. if (user != null) {
  444. const UserGroupRelation = crowi.model('UserGroupRelation');
  445. userGroups = await UserGroupRelation.findAllUserGroupIdsRelatedToUser(user);
  446. }
  447. return builder.addConditionToFilteringByViewer(user, userGroups, showAnyoneKnowsLink, !hidePagesRestrictedByOwner, !hidePagesRestrictedByGroup);
  448. }
  449. /**
  450. * Add condition that filter pages by viewer
  451. * by considering Config
  452. *
  453. * @param {PageQueryBuilder} builder
  454. * @param {User} user
  455. * @param {boolean} showAnyoneKnowsLink
  456. */
  457. async function addConditionToFilteringByViewerToEdit(builder, user) {
  458. validateCrowi();
  459. // determine UserGroup condition
  460. let userGroups = null;
  461. if (user != null) {
  462. const UserGroupRelation = crowi.model('UserGroupRelation');
  463. userGroups = await UserGroupRelation.findAllUserGroupIdsRelatedToUser(user);
  464. }
  465. return builder.addConditionToFilteringByViewer(user, userGroups, false, false, false);
  466. }
  467. /**
  468. * export addConditionToFilteringByViewerForList as static method
  469. */
  470. pageSchema.statics.addConditionToFilteringByViewerForList = addConditionToFilteringByViewerForList;
  471. /**
  472. * export addConditionToFilteringByViewerToEdit as static method
  473. */
  474. pageSchema.statics.addConditionToFilteringByViewerToEdit = addConditionToFilteringByViewerToEdit;
  475. /**
  476. * Throw error for growi-lsx-plugin (v1.x)
  477. */
  478. pageSchema.statics.generateQueryToListByStartWith = function(path, user, option) {
  479. const dummyQuery = this.find();
  480. dummyQuery.exec = async() => {
  481. throw new Error('Plugin version mismatch. Upgrade growi-lsx-plugin to v2.0.0 or above.');
  482. };
  483. return dummyQuery;
  484. };
  485. pageSchema.statics.generateQueryToListWithDescendants = pageSchema.statics.generateQueryToListByStartWith;
  486. /**
  487. * find all templates applicable to the new page
  488. */
  489. pageSchema.statics.findTemplate = async function(path) {
  490. const templatePath = nodePath.posix.dirname(path);
  491. const pathList = generatePathsOnTree(path, []);
  492. const regexpList = pathList.map((path) => {
  493. const pathWithTrailingSlash = pathUtils.addTrailingSlash(path);
  494. return new RegExp(`^${escapeStringRegexp(pathWithTrailingSlash)}_{1,2}template$`);
  495. });
  496. const templatePages = await this.find({ path: { $in: regexpList } })
  497. .populate({ path: 'revision', model: 'Revision' })
  498. .exec();
  499. return fetchTemplate(templatePages, templatePath);
  500. };
  501. const generatePathsOnTree = (path, pathList) => {
  502. pathList.push(path);
  503. if (path === '/') {
  504. return pathList;
  505. }
  506. const newPath = nodePath.posix.dirname(path);
  507. return generatePathsOnTree(newPath, pathList);
  508. };
  509. const assignTemplateByType = (templates, path, type) => {
  510. const targetTemplatePath = urljoin(path, `${type}template`);
  511. return templates.find((template) => {
  512. return (template.path === targetTemplatePath);
  513. });
  514. };
  515. const assignDecendantsTemplate = (decendantsTemplates, path) => {
  516. const decendantsTemplate = assignTemplateByType(decendantsTemplates, path, '__');
  517. if (decendantsTemplate) {
  518. return decendantsTemplate;
  519. }
  520. if (path === '/') {
  521. return;
  522. }
  523. const newPath = nodePath.posix.dirname(path);
  524. return assignDecendantsTemplate(decendantsTemplates, newPath);
  525. };
  526. const fetchTemplate = async(templates, templatePath) => {
  527. let templateBody;
  528. let templateTags;
  529. /**
  530. * get children template
  531. * __tempate: applicable only to immediate decendants
  532. */
  533. const childrenTemplate = assignTemplateByType(templates, templatePath, '_');
  534. /**
  535. * get decendants templates
  536. * _tempate: applicable to all pages under
  537. */
  538. const decendantsTemplate = assignDecendantsTemplate(templates, templatePath);
  539. if (childrenTemplate) {
  540. templateBody = childrenTemplate.revision.body;
  541. templateTags = await childrenTemplate.findRelatedTagsById();
  542. }
  543. else if (decendantsTemplate) {
  544. templateBody = decendantsTemplate.revision.body;
  545. templateTags = await decendantsTemplate.findRelatedTagsById();
  546. }
  547. return { templateBody, templateTags };
  548. };
  549. async function pushRevision(pageData, newRevision, user) {
  550. await newRevision.save();
  551. debug('Successfully saved new revision', newRevision);
  552. pageData.revision = newRevision;
  553. pageData.lastUpdateUser = user;
  554. pageData.updatedAt = Date.now();
  555. return pageData.save();
  556. }
  557. async function validateAppliedScope(user, grant, grantUserGroupId) {
  558. if (grant === GRANT_USER_GROUP && grantUserGroupId == null) {
  559. throw new Error('grant userGroupId is not specified');
  560. }
  561. if (grant === GRANT_USER_GROUP) {
  562. const UserGroupRelation = crowi.model('UserGroupRelation');
  563. const count = await UserGroupRelation.countByGroupIdAndUser(grantUserGroupId, user);
  564. if (count === 0) {
  565. throw new Error('no relations were exist for group and user.');
  566. }
  567. }
  568. }
  569. pageSchema.statics.createV4 = async function(path, body, user, options = {}) {
  570. /*
  571. * v4 compatible process
  572. */
  573. validateCrowi();
  574. const Page = this;
  575. const Revision = crowi.model('Revision');
  576. const format = options.format || 'markdown';
  577. const grantUserGroupId = options.grantUserGroupId || null;
  578. // sanitize path
  579. path = crowi.xss.process(path); // eslint-disable-line no-param-reassign
  580. let grant = options.grant;
  581. // force public
  582. if (isTopPage(path)) {
  583. grant = GRANT_PUBLIC;
  584. }
  585. const isExist = await this.count({ path });
  586. if (isExist) {
  587. throw new Error('Cannot create new page to existed path');
  588. }
  589. const page = new Page();
  590. page.path = path;
  591. page.creator = user;
  592. page.lastUpdateUser = user;
  593. page.status = STATUS_PUBLISHED;
  594. await validateAppliedScope(user, grant, grantUserGroupId);
  595. page.applyScope(user, grant, grantUserGroupId);
  596. let savedPage = await page.save();
  597. const newRevision = Revision.prepareRevision(savedPage, body, null, user, { format });
  598. savedPage = await pushRevision(savedPage, newRevision, user);
  599. await savedPage.populateDataToShowRevision();
  600. pageEvent.emit('create', savedPage, user);
  601. return savedPage;
  602. };
  603. pageSchema.statics.updatePageV4 = async function(pageData, body, previousBody, user, options = {}) {
  604. validateCrowi();
  605. const Revision = crowi.model('Revision');
  606. const grant = options.grant || pageData.grant; // use the previous data if absence
  607. const grantUserGroupId = options.grantUserGroupId || pageData.grantUserGroupId; // use the previous data if absence
  608. const isSyncRevisionToHackmd = options.isSyncRevisionToHackmd;
  609. await validateAppliedScope(user, grant, grantUserGroupId);
  610. pageData.applyScope(user, grant, grantUserGroupId);
  611. // update existing page
  612. let savedPage = await pageData.save();
  613. const newRevision = await Revision.prepareRevision(pageData, body, previousBody, user);
  614. savedPage = await pushRevision(savedPage, newRevision, user);
  615. await savedPage.populateDataToShowRevision();
  616. if (isSyncRevisionToHackmd) {
  617. savedPage = await this.syncRevisionToHackmd(savedPage);
  618. }
  619. pageEvent.emit('update', savedPage, user);
  620. return savedPage;
  621. };
  622. pageSchema.statics.applyScopesToDescendantsAsyncronously = async function(parentPage, user) {
  623. const builder = new this.PageQueryBuilder(this.find());
  624. builder.addConditionToListWithDescendants(parentPage.path);
  625. // add grant conditions
  626. await addConditionToFilteringByViewerToEdit(builder, user);
  627. // get all pages that the specified user can update
  628. const pages = await builder.query.exec();
  629. for (const page of pages) {
  630. // skip parentPage
  631. if (page.id === parentPage.id) {
  632. continue;
  633. }
  634. page.applyScope(user, parentPage.grant, parentPage.grantedGroup);
  635. page.save();
  636. }
  637. };
  638. pageSchema.statics.removeByPath = function(path) {
  639. if (path == null) {
  640. throw new Error('path is required');
  641. }
  642. return this.findOneAndRemove({ path }).exec();
  643. };
  644. pageSchema.statics.findListByPathsArray = async function(paths, includeEmpty = false) {
  645. const queryBuilder = new this.PageQueryBuilder(this.find(), includeEmpty);
  646. queryBuilder.addConditionToListByPathsArray(paths);
  647. return await queryBuilder.query.exec();
  648. };
  649. pageSchema.statics.publicizePages = async function(pages) {
  650. const operationsToPublicize = pages.map((page) => {
  651. return {
  652. updateOne: {
  653. filter: { _id: page._id },
  654. update: {
  655. grantedGroup: null,
  656. grant: this.GRANT_PUBLIC,
  657. },
  658. },
  659. };
  660. });
  661. await this.bulkWrite(operationsToPublicize);
  662. };
  663. pageSchema.statics.transferPagesToGroup = async function(pages, transferToUserGroupId) {
  664. const UserGroup = mongoose.model('UserGroup');
  665. if ((await UserGroup.count({ _id: transferToUserGroupId })) === 0) {
  666. throw Error('Cannot find the group to which private pages belong to. _id: ', transferToUserGroupId);
  667. }
  668. await this.updateMany({ _id: { $in: pages.map(p => p._id) } }, { grantedGroup: transferToUserGroupId });
  669. };
  670. /**
  671. * associate GROWI page and HackMD page
  672. * @param {Page} pageData
  673. * @param {string} pageIdOnHackmd
  674. */
  675. pageSchema.statics.registerHackmdPage = function(pageData, pageIdOnHackmd) {
  676. pageData.pageIdOnHackmd = pageIdOnHackmd;
  677. return this.syncRevisionToHackmd(pageData);
  678. };
  679. /**
  680. * update revisionHackmdSynced
  681. * @param {Page} pageData
  682. * @param {bool} isSave whether save or not
  683. */
  684. pageSchema.statics.syncRevisionToHackmd = function(pageData, isSave = true) {
  685. pageData.revisionHackmdSynced = pageData.revision;
  686. pageData.hasDraftOnHackmd = false;
  687. let returnData = pageData;
  688. if (isSave) {
  689. returnData = pageData.save();
  690. }
  691. return returnData;
  692. };
  693. /**
  694. * update hasDraftOnHackmd
  695. * !! This will be invoked many time from many people !!
  696. *
  697. * @param {Page} pageData
  698. * @param {Boolean} newValue
  699. */
  700. pageSchema.statics.updateHasDraftOnHackmd = async function(pageData, newValue) {
  701. if (pageData.hasDraftOnHackmd === newValue) {
  702. // do nothing when hasDraftOnHackmd equals to newValue
  703. return;
  704. }
  705. pageData.hasDraftOnHackmd = newValue;
  706. return pageData.save();
  707. };
  708. pageSchema.methods.getNotificationTargetUsers = async function() {
  709. const Comment = mongoose.model('Comment');
  710. const Revision = mongoose.model('Revision');
  711. const [commentCreators, revisionAuthors] = await Promise.all([Comment.findCreatorsByPage(this), Revision.findAuthorsByPage(this)]);
  712. const targetUsers = new Set([this.creator].concat(commentCreators, revisionAuthors));
  713. return Array.from(targetUsers);
  714. };
  715. pageSchema.statics.getHistories = function() {
  716. // TODO
  717. };
  718. pageSchema.statics.STATUS_PUBLISHED = STATUS_PUBLISHED;
  719. pageSchema.statics.STATUS_DELETED = STATUS_DELETED;
  720. pageSchema.statics.GRANT_PUBLIC = GRANT_PUBLIC;
  721. pageSchema.statics.GRANT_RESTRICTED = GRANT_RESTRICTED;
  722. pageSchema.statics.GRANT_SPECIFIED = GRANT_SPECIFIED;
  723. pageSchema.statics.GRANT_OWNER = GRANT_OWNER;
  724. pageSchema.statics.GRANT_USER_GROUP = GRANT_USER_GROUP;
  725. pageSchema.statics.PAGE_GRANT_ERROR = PAGE_GRANT_ERROR;
  726. return pageSchema;
  727. };