obsolete-page.js 34 KB

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