page.js 34 KB

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