obsolete-page.js 27 KB

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