obsolete-page.js 35 KB

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