obsolete-page.js 27 KB

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