obsolete-page.js 33 KB

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