page.js 34 KB

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