obsolete-page.js 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176
  1. import { templateChecker, pagePathUtils } 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 { pathUtils } = require('@growi/core');
  12. const escapeStringRegexp = require('escape-string-regexp');
  13. const { isTopPage, isTrashPage, isUserNamePage } = 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. 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. 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 class PageQueryBuilder {
  67. constructor(query, includeEmpty = false) {
  68. this.query = query;
  69. if (!includeEmpty) {
  70. this.query = this.query
  71. .and({
  72. $or: [
  73. { isEmpty: false },
  74. { isEmpty: null }, // for v4 compatibility
  75. ],
  76. });
  77. }
  78. }
  79. addConditionToExcludeTrashed() {
  80. this.query = this.query
  81. .and({
  82. $or: [
  83. { status: null },
  84. { status: STATUS_PUBLISHED },
  85. ],
  86. });
  87. return this;
  88. }
  89. /**
  90. * generate the query to find the pages '{path}/*' and '{path}' self.
  91. * If top page, return without doing anything.
  92. */
  93. addConditionToListWithDescendants(path, option) {
  94. // No request is set for the top page
  95. if (isTopPage(path)) {
  96. return this;
  97. }
  98. const pathNormalized = pathUtils.normalizePath(path);
  99. const pathWithTrailingSlash = pathUtils.addTrailingSlash(path);
  100. const startsPattern = escapeStringRegexp(pathWithTrailingSlash);
  101. this.query = this.query
  102. .and({
  103. $or: [
  104. { path: pathNormalized },
  105. { path: new RegExp(`^${startsPattern}`) },
  106. ],
  107. });
  108. return this;
  109. }
  110. /**
  111. * generate the query to find the pages '{path}/*' (exclude '{path}' self).
  112. * If top page, return without doing anything.
  113. */
  114. addConditionToListOnlyDescendants(path, option) {
  115. // No request is set for the top page
  116. if (isTopPage(path)) {
  117. return this;
  118. }
  119. const pathWithTrailingSlash = pathUtils.addTrailingSlash(path);
  120. const startsPattern = escapeStringRegexp(pathWithTrailingSlash);
  121. this.query = this.query
  122. .and({ path: new RegExp(`^${startsPattern}`) });
  123. return this;
  124. }
  125. addConditionToListOnlyAncestors(path) {
  126. const pathNormalized = pathUtils.normalizePath(path);
  127. const ancestorsPaths = extractToAncestorsPaths(pathNormalized);
  128. this.query = this.query
  129. .and({
  130. path: {
  131. $in: ancestorsPaths,
  132. },
  133. });
  134. return this;
  135. }
  136. /**
  137. * generate the query to find pages that start with `path`
  138. *
  139. * In normal case, returns '{path}/*' and '{path}' self.
  140. * If top page, return without doing anything.
  141. *
  142. * *option*
  143. * Left for backward compatibility
  144. */
  145. addConditionToListByStartWith(path, option) {
  146. // No request is set for the top page
  147. if (isTopPage(path)) {
  148. return this;
  149. }
  150. const startsPattern = escapeStringRegexp(path);
  151. this.query = this.query
  152. .and({ path: new RegExp(`^${startsPattern}`) });
  153. return this;
  154. }
  155. addConditionToFilteringByViewer(user, userGroups, showAnyoneKnowsLink = false, showPagesRestrictedByOwner = false, showPagesRestrictedByGroup = false) {
  156. const grantConditions = [
  157. { grant: null },
  158. { grant: GRANT_PUBLIC },
  159. ];
  160. if (showAnyoneKnowsLink) {
  161. grantConditions.push({ grant: GRANT_RESTRICTED });
  162. }
  163. if (showPagesRestrictedByOwner) {
  164. grantConditions.push(
  165. { grant: GRANT_SPECIFIED },
  166. { grant: GRANT_OWNER },
  167. );
  168. }
  169. else if (user != null) {
  170. grantConditions.push(
  171. { grant: GRANT_SPECIFIED, grantedUsers: user._id },
  172. { grant: GRANT_OWNER, grantedUsers: user._id },
  173. );
  174. }
  175. if (showPagesRestrictedByGroup) {
  176. grantConditions.push(
  177. { grant: GRANT_USER_GROUP },
  178. );
  179. }
  180. else if (userGroups != null && userGroups.length > 0) {
  181. grantConditions.push(
  182. { grant: GRANT_USER_GROUP, grantedGroup: { $in: userGroups } },
  183. );
  184. }
  185. this.query = this.query
  186. .and({
  187. $or: grantConditions,
  188. });
  189. return this;
  190. }
  191. addConditionToPagenate(offset, limit, sortOpt) {
  192. this.query = this.query
  193. .sort(sortOpt).skip(offset).limit(limit); // eslint-disable-line newline-per-chained-call
  194. return this;
  195. }
  196. addConditionAsNonRootPage() {
  197. this.query = this.query.and({ path: { $ne: '/' } });
  198. return this;
  199. }
  200. addConditionAsNotMigrated() {
  201. this.query = this.query
  202. .and({ parent: null });
  203. return this;
  204. }
  205. addConditionAsMigrated() {
  206. this.query = this.query
  207. .and(
  208. {
  209. $or: [
  210. { parent: { $ne: null } },
  211. { path: '/' },
  212. ],
  213. },
  214. );
  215. return this;
  216. }
  217. /*
  218. * Add this condition when get any ancestor pages including the target's parent
  219. */
  220. addConditionToSortPagesByDescPath() {
  221. this.query = this.query.sort('-path');
  222. return this;
  223. }
  224. addConditionToSortPagesByAscPath() {
  225. this.query = this.query.sort('path');
  226. return this;
  227. }
  228. addConditionToMinimizeDataForRendering() {
  229. this.query = this.query.select('_id path isEmpty grant revision');
  230. return this;
  231. }
  232. addConditionToListByPathsArray(paths) {
  233. this.query = this.query
  234. .and({
  235. path: {
  236. $in: paths,
  237. },
  238. });
  239. return this;
  240. }
  241. addConditionToListByPageIdsArray(pageIds) {
  242. this.query = this.query
  243. .and({
  244. _id: {
  245. $in: pageIds,
  246. },
  247. });
  248. return this;
  249. }
  250. populateDataToList(userPublicFields) {
  251. this.query = this.query
  252. .populate({
  253. path: 'lastUpdateUser',
  254. select: userPublicFields,
  255. });
  256. return this;
  257. }
  258. populateDataToShowRevision(userPublicFields) {
  259. this.query = populateDataToShowRevision(this.query, userPublicFields);
  260. return this;
  261. }
  262. addConditionToFilteringByParentId(parentId) {
  263. this.query = this.query.and({ parent: parentId });
  264. return this;
  265. }
  266. }
  267. export const getPageSchema = (crowi) => {
  268. let pageEvent;
  269. // init event
  270. if (crowi != null) {
  271. pageEvent = crowi.event('page');
  272. pageEvent.on('create', pageEvent.onCreate);
  273. pageEvent.on('update', pageEvent.onUpdate);
  274. pageEvent.on('createMany', pageEvent.onCreateMany);
  275. pageEvent.on('addSeenUsers', pageEvent.onAddSeenUsers);
  276. }
  277. function validateCrowi() {
  278. if (crowi == null) {
  279. throw new Error('"crowi" is null. Init User model with "crowi" argument first.');
  280. }
  281. }
  282. pageSchema.methods.isDeleted = function() {
  283. return (this.status === STATUS_DELETED) || isTrashPage(this.path);
  284. };
  285. pageSchema.methods.isPublic = function() {
  286. if (!this.grant || this.grant === GRANT_PUBLIC) {
  287. return true;
  288. }
  289. return false;
  290. };
  291. pageSchema.methods.isTopPage = function() {
  292. return isTopPage(this.path);
  293. };
  294. pageSchema.methods.isTemplate = function() {
  295. return checkTemplatePath(this.path);
  296. };
  297. pageSchema.methods.isLatestRevision = function() {
  298. // populate されていなくて判断できない
  299. if (!this.latestRevision || !this.revision) {
  300. return true;
  301. }
  302. // comparing ObjectId with string
  303. // eslint-disable-next-line eqeqeq
  304. return (this.latestRevision == this.revision._id.toString());
  305. };
  306. pageSchema.methods.findRelatedTagsById = async function() {
  307. const PageTagRelation = mongoose.model('PageTagRelation');
  308. const relations = await PageTagRelation.find({ relatedPage: this._id }).populate('relatedTag');
  309. return relations.map((relation) => { return relation.relatedTag.name });
  310. };
  311. pageSchema.methods.isUpdatable = function(previousRevision) {
  312. const revision = this.latestRevision || this.revision;
  313. // comparing ObjectId with string
  314. // eslint-disable-next-line eqeqeq
  315. if (revision != previousRevision) {
  316. return false;
  317. }
  318. return true;
  319. };
  320. pageSchema.methods.isLiked = function(user) {
  321. if (user == null || user._id == null) {
  322. return false;
  323. }
  324. return this.liker.some((likedUserId) => {
  325. return likedUserId.toString() === user._id.toString();
  326. });
  327. };
  328. pageSchema.methods.like = function(userData) {
  329. const self = this;
  330. return new Promise(((resolve, reject) => {
  331. const added = self.liker.addToSet(userData._id);
  332. if (added.length > 0) {
  333. self.save((err, data) => {
  334. if (err) {
  335. return reject(err);
  336. }
  337. logger.debug('liker updated!', added);
  338. return resolve(data);
  339. });
  340. }
  341. else {
  342. logger.debug('liker not updated');
  343. return reject(new Error('Already liked'));
  344. }
  345. }));
  346. };
  347. pageSchema.methods.unlike = function(userData, callback) {
  348. const self = this;
  349. return new Promise(((resolve, reject) => {
  350. const beforeCount = self.liker.length;
  351. self.liker.pull(userData._id);
  352. if (self.liker.length !== beforeCount) {
  353. self.save((err, data) => {
  354. if (err) {
  355. return reject(err);
  356. }
  357. return resolve(data);
  358. });
  359. }
  360. else {
  361. logger.debug('liker not updated');
  362. return reject(new Error('Already unliked'));
  363. }
  364. }));
  365. };
  366. pageSchema.methods.isSeenUser = function(userData) {
  367. return this.seenUsers.includes(userData._id);
  368. };
  369. pageSchema.methods.seen = async function(userData) {
  370. if (this.isSeenUser(userData)) {
  371. debug('seenUsers not updated');
  372. return this;
  373. }
  374. if (!userData || !userData._id) {
  375. throw new Error('User data is not valid');
  376. }
  377. const added = this.seenUsers.addToSet(userData._id);
  378. const saved = await this.save();
  379. debug('seenUsers updated!', added);
  380. pageEvent.emit('addSeenUsers', saved);
  381. return saved;
  382. };
  383. pageSchema.methods.updateSlackChannels = function(slackChannels) {
  384. this.slackChannels = slackChannels;
  385. return this.save();
  386. };
  387. pageSchema.methods.initLatestRevisionField = async function(revisionId) {
  388. this.latestRevision = this.revision;
  389. if (revisionId != null) {
  390. this.revision = revisionId;
  391. }
  392. };
  393. pageSchema.methods.populateDataToShowRevision = async function() {
  394. validateCrowi();
  395. const User = crowi.model('User');
  396. return populateDataToShowRevision(this, User.USER_FIELDS_EXCEPT_CONFIDENTIAL);
  397. };
  398. pageSchema.methods.populateDataToMakePresentation = async function(revisionId) {
  399. this.latestRevision = this.revision;
  400. if (revisionId != null) {
  401. this.revision = revisionId;
  402. }
  403. return this.populate('revision');
  404. };
  405. pageSchema.methods.applyScope = function(user, grant, grantUserGroupId) {
  406. // reset
  407. this.grantedUsers = [];
  408. this.grantedGroup = null;
  409. this.grant = grant || GRANT_PUBLIC;
  410. if (grant !== GRANT_PUBLIC && grant !== GRANT_USER_GROUP) {
  411. this.grantedUsers.push(user._id);
  412. }
  413. if (grant === GRANT_USER_GROUP) {
  414. this.grantedGroup = grantUserGroupId;
  415. }
  416. };
  417. pageSchema.methods.getContentAge = function() {
  418. return differenceInYears(new Date(), this.updatedAt);
  419. };
  420. pageSchema.statics.updateCommentCount = function(pageId) {
  421. validateCrowi();
  422. const self = this;
  423. const Comment = crowi.model('Comment');
  424. return Comment.countCommentByPageId(pageId)
  425. .then((count) => {
  426. self.update({ _id: pageId }, { commentCount: count }, {}, (err, data) => {
  427. if (err) {
  428. debug('Update commentCount Error', err);
  429. throw err;
  430. }
  431. return data;
  432. });
  433. });
  434. };
  435. pageSchema.statics.getGrantLabels = function() {
  436. const grantLabels = {};
  437. grantLabels[GRANT_PUBLIC] = 'Public'; // 公開
  438. grantLabels[GRANT_RESTRICTED] = 'Anyone with the link'; // リンクを知っている人のみ
  439. // grantLabels[GRANT_SPECIFIED] = 'Specified users only'; // 特定ユーザーのみ
  440. grantLabels[GRANT_USER_GROUP] = 'Only inside the group'; // 特定グループのみ
  441. grantLabels[GRANT_OWNER] = 'Only me'; // 自分のみ
  442. return grantLabels;
  443. };
  444. pageSchema.statics.getUserPagePath = function(user) {
  445. return `/user/${user.username}`;
  446. };
  447. pageSchema.statics.getDeletedPageName = function(path) {
  448. if (path.match('/')) {
  449. // eslint-disable-next-line no-param-reassign
  450. path = path.substr(1);
  451. }
  452. return `/trash/${path}`;
  453. };
  454. pageSchema.statics.getRevertDeletedPageName = function(path) {
  455. return path.replace('/trash', '');
  456. };
  457. pageSchema.statics.isDeletableName = function(path) {
  458. return !isTopPage(path) && !isUserNamePage(path);
  459. };
  460. pageSchema.statics.fixToCreatableName = function(path) {
  461. return path
  462. .replace(/\/\//g, '/');
  463. };
  464. pageSchema.statics.updateRevision = function(pageId, revisionId, cb) {
  465. this.update({ _id: pageId }, { revision: revisionId }, {}, (err, data) => {
  466. cb(err, data);
  467. });
  468. };
  469. /**
  470. * return whether the user is accessible to the page
  471. * @param {string} id ObjectId
  472. * @param {User} user
  473. */
  474. pageSchema.statics.isAccessiblePageByViewer = async function(id, user) {
  475. const baseQuery = this.count({ _id: id });
  476. let userGroups = [];
  477. if (user != null) {
  478. validateCrowi();
  479. const UserGroupRelation = crowi.model('UserGroupRelation');
  480. userGroups = await UserGroupRelation.findAllUserGroupIdsRelatedToUser(user);
  481. }
  482. const queryBuilder = new PageQueryBuilder(baseQuery);
  483. queryBuilder.addConditionToFilteringByViewer(user, userGroups, true);
  484. const count = await queryBuilder.query.exec();
  485. return count > 0;
  486. };
  487. /**
  488. * @param {string} id ObjectId
  489. * @param {User} user User instance
  490. * @param {UserGroup[]} userGroups List of UserGroup instances
  491. */
  492. pageSchema.statics.findByIdAndViewer = async function(id, user, userGroups, includeEmpty = false) {
  493. const baseQuery = this.findOne({ _id: id });
  494. let relatedUserGroups = userGroups;
  495. if (user != null && relatedUserGroups == null) {
  496. validateCrowi();
  497. const UserGroupRelation = crowi.model('UserGroupRelation');
  498. relatedUserGroups = await UserGroupRelation.findAllUserGroupIdsRelatedToUser(user);
  499. }
  500. const queryBuilder = new PageQueryBuilder(baseQuery, includeEmpty);
  501. queryBuilder.addConditionToFilteringByViewer(user, relatedUserGroups, true);
  502. return queryBuilder.query.exec();
  503. };
  504. pageSchema.statics.findByIdAndViewerToEdit = async function(id, user, includeEmpty = false) {
  505. const baseQuery = this.findOne({ _id: id });
  506. const queryBuilder = new PageQueryBuilder(baseQuery, includeEmpty);
  507. // add grant conditions
  508. await addConditionToFilteringByViewerToEdit(queryBuilder, user);
  509. return queryBuilder.query.exec();
  510. };
  511. // find page by path
  512. pageSchema.statics.findByPath = function(path, includeEmpty = false) {
  513. if (path == null) {
  514. return null;
  515. }
  516. const builder = new PageQueryBuilder(this.findOne({ path }), includeEmpty);
  517. return builder.query.exec();
  518. };
  519. /**
  520. * @param {string} path Page path
  521. * @param {User} user User instance
  522. * @param {UserGroup[]} userGroups List of UserGroup instances
  523. */
  524. pageSchema.statics.findAncestorByPathAndViewer = async function(path, user, userGroups, includeEmpty = false) {
  525. if (path == null) {
  526. throw new Error('path is required.');
  527. }
  528. if (path === '/') {
  529. return null;
  530. }
  531. const ancestorsPaths = extractToAncestorsPaths(path);
  532. // pick the longest one
  533. const baseQuery = this.findOne({ path: { $in: ancestorsPaths } }).sort({ path: -1 });
  534. let relatedUserGroups = userGroups;
  535. if (user != null && relatedUserGroups == null) {
  536. validateCrowi();
  537. const UserGroupRelation = crowi.model('UserGroupRelation');
  538. relatedUserGroups = await UserGroupRelation.findAllUserGroupIdsRelatedToUser(user);
  539. }
  540. const queryBuilder = new PageQueryBuilder(baseQuery, includeEmpty);
  541. queryBuilder.addConditionToFilteringByViewer(user, relatedUserGroups);
  542. return queryBuilder.query.exec();
  543. };
  544. /**
  545. * find pages that is match with `path` and its descendants
  546. */
  547. pageSchema.statics.findListWithDescendants = async function(path, user, option = {}, includeEmpty = false) {
  548. const builder = new PageQueryBuilder(this.find(), includeEmpty);
  549. builder.addConditionToListWithDescendants(path, option);
  550. return findListFromBuilderAndViewer(builder, user, false, option);
  551. };
  552. /**
  553. * find pages that is match with `path` and its descendants whitch user is able to manage
  554. */
  555. pageSchema.statics.findManageableListWithDescendants = async function(page, user, option = {}, includeEmpty = false) {
  556. if (user == null) {
  557. return null;
  558. }
  559. const builder = new PageQueryBuilder(this.find(), includeEmpty);
  560. builder.addConditionToListWithDescendants(page.path, option);
  561. // add grant conditions
  562. await addConditionToFilteringByViewerToEdit(builder, user);
  563. const { pages } = await findListFromBuilderAndViewer(builder, user, false, option);
  564. // add page if 'grant' is GRANT_RESTRICTED
  565. // because addConditionToListWithDescendants excludes GRANT_RESTRICTED pages
  566. if (page.grant === GRANT_RESTRICTED) {
  567. pages.push(page);
  568. }
  569. return pages;
  570. };
  571. /**
  572. * find pages that start with `path`
  573. */
  574. pageSchema.statics.findListByStartWith = async function(path, user, option, includeEmpty = false) {
  575. const builder = new PageQueryBuilder(this.find(), includeEmpty);
  576. builder.addConditionToListByStartWith(path, option);
  577. return findListFromBuilderAndViewer(builder, user, false, option);
  578. };
  579. /**
  580. * find pages that is created by targetUser
  581. *
  582. * @param {User} targetUser
  583. * @param {User} currentUser
  584. * @param {any} option
  585. */
  586. pageSchema.statics.findListByCreator = async function(targetUser, currentUser, option) {
  587. const opt = Object.assign({ sort: 'createdAt', desc: -1 }, option);
  588. const builder = new PageQueryBuilder(this.find({ creator: targetUser._id }));
  589. let showAnyoneKnowsLink = null;
  590. if (targetUser != null && currentUser != null) {
  591. showAnyoneKnowsLink = targetUser._id.equals(currentUser._id);
  592. }
  593. return await findListFromBuilderAndViewer(builder, currentUser, showAnyoneKnowsLink, opt);
  594. };
  595. pageSchema.statics.findListByPageIds = async function(ids, option = {}, shouldIncludeEmpty = false) {
  596. const User = crowi.model('User');
  597. const opt = Object.assign({}, option);
  598. const builder = new PageQueryBuilder(this.find({ _id: { $in: ids } }), shouldIncludeEmpty);
  599. builder.addConditionToPagenate(opt.offset, opt.limit);
  600. // count
  601. const totalCount = await builder.query.exec('count');
  602. // find
  603. builder.populateDataToList(User.USER_FIELDS_EXCEPT_CONFIDENTIAL);
  604. const pages = await builder.query.clone().exec('find');
  605. const result = {
  606. pages, totalCount, offset: opt.offset, limit: opt.limit,
  607. };
  608. return result;
  609. };
  610. /**
  611. * find pages by PageQueryBuilder
  612. * @param {PageQueryBuilder} builder
  613. * @param {User} user
  614. * @param {boolean} showAnyoneKnowsLink
  615. * @param {any} option
  616. */
  617. async function findListFromBuilderAndViewer(builder, user, showAnyoneKnowsLink, option) {
  618. validateCrowi();
  619. const User = crowi.model('User');
  620. const opt = Object.assign({ sort: 'updatedAt', desc: -1 }, option);
  621. const sortOpt = {};
  622. sortOpt[opt.sort] = opt.desc;
  623. // exclude trashed pages
  624. if (!opt.includeTrashed) {
  625. builder.addConditionToExcludeTrashed();
  626. }
  627. // add grant conditions
  628. await addConditionToFilteringByViewerForList(builder, user, showAnyoneKnowsLink);
  629. // count
  630. const totalCount = await builder.query.exec('count');
  631. // find
  632. builder.addConditionToPagenate(opt.offset, opt.limit, sortOpt);
  633. builder.populateDataToList(User.USER_FIELDS_EXCEPT_CONFIDENTIAL);
  634. const pages = await builder.query.lean().clone().exec('find');
  635. const result = {
  636. pages, totalCount, offset: opt.offset, limit: opt.limit,
  637. };
  638. return result;
  639. }
  640. /**
  641. * Add condition that filter pages by viewer
  642. * by considering Config
  643. *
  644. * @param {PageQueryBuilder} builder
  645. * @param {User} user
  646. * @param {boolean} showAnyoneKnowsLink
  647. */
  648. async function addConditionToFilteringByViewerForList(builder, user, showAnyoneKnowsLink) {
  649. validateCrowi();
  650. // determine User condition
  651. const hidePagesRestrictedByOwner = crowi.configManager.getConfig('crowi', 'security:list-policy:hideRestrictedByOwner');
  652. const hidePagesRestrictedByGroup = crowi.configManager.getConfig('crowi', 'security:list-policy:hideRestrictedByGroup');
  653. // determine UserGroup condition
  654. let userGroups = null;
  655. if (user != null) {
  656. const UserGroupRelation = crowi.model('UserGroupRelation');
  657. userGroups = await UserGroupRelation.findAllUserGroupIdsRelatedToUser(user);
  658. }
  659. return builder.addConditionToFilteringByViewer(user, userGroups, showAnyoneKnowsLink, !hidePagesRestrictedByOwner, !hidePagesRestrictedByGroup);
  660. }
  661. /**
  662. * Add condition that filter pages by viewer
  663. * by considering Config
  664. *
  665. * @param {PageQueryBuilder} builder
  666. * @param {User} user
  667. * @param {boolean} showAnyoneKnowsLink
  668. */
  669. async function addConditionToFilteringByViewerToEdit(builder, user) {
  670. validateCrowi();
  671. // determine UserGroup condition
  672. let userGroups = null;
  673. if (user != null) {
  674. const UserGroupRelation = crowi.model('UserGroupRelation');
  675. userGroups = await UserGroupRelation.findAllUserGroupIdsRelatedToUser(user);
  676. }
  677. return builder.addConditionToFilteringByViewer(user, userGroups, false, false, false);
  678. }
  679. /**
  680. * export addConditionToFilteringByViewerForList as static method
  681. */
  682. pageSchema.statics.addConditionToFilteringByViewerForList = addConditionToFilteringByViewerForList;
  683. /**
  684. * export addConditionToFilteringByViewerToEdit as static method
  685. */
  686. pageSchema.statics.addConditionToFilteringByViewerToEdit = addConditionToFilteringByViewerToEdit;
  687. /**
  688. * Throw error for growi-lsx-plugin (v1.x)
  689. */
  690. pageSchema.statics.generateQueryToListByStartWith = function(path, user, option) {
  691. const dummyQuery = this.find();
  692. dummyQuery.exec = async() => {
  693. throw new Error('Plugin version mismatch. Upgrade growi-lsx-plugin to v2.0.0 or above.');
  694. };
  695. return dummyQuery;
  696. };
  697. pageSchema.statics.generateQueryToListWithDescendants = pageSchema.statics.generateQueryToListByStartWith;
  698. /**
  699. * find all templates applicable to the new page
  700. */
  701. pageSchema.statics.findTemplate = async function(path) {
  702. const templatePath = nodePath.posix.dirname(path);
  703. const pathList = generatePathsOnTree(path, []);
  704. const regexpList = pathList.map((path) => {
  705. const pathWithTrailingSlash = pathUtils.addTrailingSlash(path);
  706. return new RegExp(`^${escapeStringRegexp(pathWithTrailingSlash)}_{1,2}template$`);
  707. });
  708. const templatePages = await this.find({ path: { $in: regexpList } })
  709. .populate({ path: 'revision', model: 'Revision' })
  710. .exec();
  711. return fetchTemplate(templatePages, templatePath);
  712. };
  713. const generatePathsOnTree = (path, pathList) => {
  714. pathList.push(path);
  715. if (path === '/') {
  716. return pathList;
  717. }
  718. const newPath = nodePath.posix.dirname(path);
  719. return generatePathsOnTree(newPath, pathList);
  720. };
  721. const assignTemplateByType = (templates, path, type) => {
  722. const targetTemplatePath = urljoin(path, `${type}template`);
  723. return templates.find((template) => {
  724. return (template.path === targetTemplatePath);
  725. });
  726. };
  727. const assignDecendantsTemplate = (decendantsTemplates, path) => {
  728. const decendantsTemplate = assignTemplateByType(decendantsTemplates, path, '__');
  729. if (decendantsTemplate) {
  730. return decendantsTemplate;
  731. }
  732. if (path === '/') {
  733. return;
  734. }
  735. const newPath = nodePath.posix.dirname(path);
  736. return assignDecendantsTemplate(decendantsTemplates, newPath);
  737. };
  738. const fetchTemplate = async(templates, templatePath) => {
  739. let templateBody;
  740. let templateTags;
  741. /**
  742. * get children template
  743. * __tempate: applicable only to immediate decendants
  744. */
  745. const childrenTemplate = assignTemplateByType(templates, templatePath, '_');
  746. /**
  747. * get decendants templates
  748. * _tempate: applicable to all pages under
  749. */
  750. const decendantsTemplate = assignDecendantsTemplate(templates, templatePath);
  751. if (childrenTemplate) {
  752. templateBody = childrenTemplate.revision.body;
  753. templateTags = await childrenTemplate.findRelatedTagsById();
  754. }
  755. else if (decendantsTemplate) {
  756. templateBody = decendantsTemplate.revision.body;
  757. templateTags = await decendantsTemplate.findRelatedTagsById();
  758. }
  759. return { templateBody, templateTags };
  760. };
  761. async function pushRevision(pageData, newRevision, user) {
  762. await newRevision.save();
  763. debug('Successfully saved new revision', newRevision);
  764. pageData.revision = newRevision;
  765. pageData.lastUpdateUser = user;
  766. pageData.updatedAt = Date.now();
  767. return pageData.save();
  768. }
  769. async function validateAppliedScope(user, grant, grantUserGroupId) {
  770. if (grant === GRANT_USER_GROUP && grantUserGroupId == null) {
  771. throw new Error('grant userGroupId is not specified');
  772. }
  773. if (grant === GRANT_USER_GROUP) {
  774. const UserGroupRelation = crowi.model('UserGroupRelation');
  775. const count = await UserGroupRelation.countByGroupIdAndUser(grantUserGroupId, user);
  776. if (count === 0) {
  777. throw new Error('no relations were exist for group and user.');
  778. }
  779. }
  780. }
  781. pageSchema.statics.createV4 = async function(path, body, user, options = {}) {
  782. /*
  783. * v4 compatible process
  784. */
  785. validateCrowi();
  786. const Page = this;
  787. const Revision = crowi.model('Revision');
  788. const format = options.format || 'markdown';
  789. const grantUserGroupId = options.grantUserGroupId || null;
  790. // sanitize path
  791. path = crowi.xss.process(path); // eslint-disable-line no-param-reassign
  792. let grant = options.grant;
  793. // force public
  794. if (isTopPage(path)) {
  795. grant = GRANT_PUBLIC;
  796. }
  797. const isExist = await this.count({ path });
  798. if (isExist) {
  799. throw new Error('Cannot create new page to existed path');
  800. }
  801. const page = new Page();
  802. page.path = path;
  803. page.creator = user;
  804. page.lastUpdateUser = user;
  805. page.status = STATUS_PUBLISHED;
  806. await validateAppliedScope(user, grant, grantUserGroupId);
  807. page.applyScope(user, grant, grantUserGroupId);
  808. let savedPage = await page.save();
  809. const newRevision = Revision.prepareRevision(savedPage, body, null, user, { format });
  810. savedPage = await pushRevision(savedPage, newRevision, user);
  811. await savedPage.populateDataToShowRevision();
  812. pageEvent.emit('create', savedPage, user);
  813. return savedPage;
  814. };
  815. pageSchema.statics.updatePageV4 = async function(pageData, body, previousBody, user, options = {}) {
  816. validateCrowi();
  817. const Revision = crowi.model('Revision');
  818. const grant = options.grant || pageData.grant; // use the previous data if absence
  819. const grantUserGroupId = options.grantUserGroupId || pageData.grantUserGroupId; // use the previous data if absence
  820. const isSyncRevisionToHackmd = options.isSyncRevisionToHackmd;
  821. await validateAppliedScope(user, grant, grantUserGroupId);
  822. pageData.applyScope(user, grant, grantUserGroupId);
  823. // update existing page
  824. let savedPage = await pageData.save();
  825. const newRevision = await Revision.prepareRevision(pageData, body, previousBody, user);
  826. savedPage = await pushRevision(savedPage, newRevision, user);
  827. await savedPage.populateDataToShowRevision();
  828. if (isSyncRevisionToHackmd) {
  829. savedPage = await this.syncRevisionToHackmd(savedPage);
  830. }
  831. pageEvent.emit('update', savedPage, user);
  832. return savedPage;
  833. };
  834. pageSchema.statics.applyScopesToDescendantsAsyncronously = async function(parentPage, user) {
  835. const builder = new PageQueryBuilder(this.find());
  836. builder.addConditionToListWithDescendants(parentPage.path);
  837. // add grant conditions
  838. await addConditionToFilteringByViewerToEdit(builder, user);
  839. // get all pages that the specified user can update
  840. const pages = await builder.query.exec();
  841. for (const page of pages) {
  842. // skip parentPage
  843. if (page.id === parentPage.id) {
  844. continue;
  845. }
  846. page.applyScope(user, parentPage.grant, parentPage.grantedGroup);
  847. page.save();
  848. }
  849. };
  850. pageSchema.statics.removeByPath = function(path) {
  851. if (path == null) {
  852. throw new Error('path is required');
  853. }
  854. return this.findOneAndRemove({ path }).exec();
  855. };
  856. pageSchema.statics.findListByPathsArray = async function(paths, includeEmpty = false) {
  857. const queryBuilder = new PageQueryBuilder(this.find(), includeEmpty);
  858. queryBuilder.addConditionToListByPathsArray(paths);
  859. return await queryBuilder.query.exec();
  860. };
  861. pageSchema.statics.publicizePages = async function(pages) {
  862. const operationsToPublicize = pages.map((page) => {
  863. return {
  864. updateOne: {
  865. filter: { _id: page._id },
  866. update: {
  867. grantedGroup: null,
  868. grant: this.GRANT_PUBLIC,
  869. },
  870. },
  871. };
  872. });
  873. await this.bulkWrite(operationsToPublicize);
  874. };
  875. pageSchema.statics.transferPagesToGroup = async function(pages, transferToUserGroupId) {
  876. const UserGroup = mongoose.model('UserGroup');
  877. if ((await UserGroup.count({ _id: transferToUserGroupId })) === 0) {
  878. throw Error('Cannot find the group to which private pages belong to. _id: ', transferToUserGroupId);
  879. }
  880. await this.updateMany({ _id: { $in: pages.map(p => p._id) } }, { grantedGroup: transferToUserGroupId });
  881. };
  882. /**
  883. * associate GROWI page and HackMD page
  884. * @param {Page} pageData
  885. * @param {string} pageIdOnHackmd
  886. */
  887. pageSchema.statics.registerHackmdPage = function(pageData, pageIdOnHackmd) {
  888. pageData.pageIdOnHackmd = pageIdOnHackmd;
  889. return this.syncRevisionToHackmd(pageData);
  890. };
  891. /**
  892. * update revisionHackmdSynced
  893. * @param {Page} pageData
  894. * @param {bool} isSave whether save or not
  895. */
  896. pageSchema.statics.syncRevisionToHackmd = function(pageData, isSave = true) {
  897. pageData.revisionHackmdSynced = pageData.revision;
  898. pageData.hasDraftOnHackmd = false;
  899. let returnData = pageData;
  900. if (isSave) {
  901. returnData = pageData.save();
  902. }
  903. return returnData;
  904. };
  905. /**
  906. * update hasDraftOnHackmd
  907. * !! This will be invoked many time from many people !!
  908. *
  909. * @param {Page} pageData
  910. * @param {Boolean} newValue
  911. */
  912. pageSchema.statics.updateHasDraftOnHackmd = async function(pageData, newValue) {
  913. if (pageData.hasDraftOnHackmd === newValue) {
  914. // do nothing when hasDraftOnHackmd equals to newValue
  915. return;
  916. }
  917. pageData.hasDraftOnHackmd = newValue;
  918. return pageData.save();
  919. };
  920. pageSchema.methods.getNotificationTargetUsers = async function() {
  921. const Comment = mongoose.model('Comment');
  922. const Revision = mongoose.model('Revision');
  923. const [commentCreators, revisionAuthors] = await Promise.all([Comment.findCreatorsByPage(this), Revision.findAuthorsByPage(this)]);
  924. const targetUsers = new Set([this.creator].concat(commentCreators, revisionAuthors));
  925. return Array.from(targetUsers);
  926. };
  927. pageSchema.statics.getHistories = function() {
  928. // TODO
  929. };
  930. pageSchema.statics.STATUS_PUBLISHED = STATUS_PUBLISHED;
  931. pageSchema.statics.STATUS_DELETED = STATUS_DELETED;
  932. pageSchema.statics.GRANT_PUBLIC = GRANT_PUBLIC;
  933. pageSchema.statics.GRANT_RESTRICTED = GRANT_RESTRICTED;
  934. pageSchema.statics.GRANT_SPECIFIED = GRANT_SPECIFIED;
  935. pageSchema.statics.GRANT_OWNER = GRANT_OWNER;
  936. pageSchema.statics.GRANT_USER_GROUP = GRANT_USER_GROUP;
  937. pageSchema.statics.PAGE_GRANT_ERROR = PAGE_GRANT_ERROR;
  938. pageSchema.statics.PageQueryBuilder = PageQueryBuilder;
  939. return pageSchema;
  940. };