page.js 34 KB

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