page.js 34 KB

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