page.js 37 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274
  1. import { templateChecker, pagePathUtils } from '@growi/core';
  2. import { listeners } from 'cluster';
  3. import loggerFactory from '~/utils/logger';
  4. // disable no-return-await for model functions
  5. /* eslint-disable no-return-await */
  6. /* eslint-disable no-use-before-define */
  7. const debug = require('debug')('growi:models:page');
  8. const nodePath = require('path');
  9. const urljoin = require('url-join');
  10. const mongoose = require('mongoose');
  11. const mongoosePaginate = require('mongoose-paginate-v2');
  12. const uniqueValidator = require('mongoose-unique-validator');
  13. const differenceInYears = require('date-fns/differenceInYears');
  14. const { pathUtils } = require('growi-commons');
  15. const escapeStringRegexp = require('escape-string-regexp');
  16. const { isTopPage, isTrashPage } = pagePathUtils;
  17. const { checkTemplatePath } = templateChecker;
  18. const logger = loggerFactory('growi:models:page');
  19. const ObjectId = mongoose.Schema.Types.ObjectId;
  20. /*
  21. * define schema
  22. */
  23. const GRANT_PUBLIC = 1;
  24. const GRANT_RESTRICTED = 2;
  25. const GRANT_SPECIFIED = 3;
  26. const GRANT_OWNER = 4;
  27. const GRANT_USER_GROUP = 5;
  28. const PAGE_GRANT_ERROR = 1;
  29. const STATUS_PUBLISHED = 'published';
  30. const STATUS_DELETED = 'deleted';
  31. const pageSchema = new mongoose.Schema({
  32. parent: {
  33. type: ObjectId, ref: 'Page', index: true, default: null,
  34. },
  35. isEmpty: { type: Boolean, default: false },
  36. path: {
  37. type: String, required: true,
  38. },
  39. revision: { type: ObjectId, ref: 'Revision' },
  40. redirectTo: { type: String, index: true },
  41. status: { type: String, default: STATUS_PUBLISHED, index: true },
  42. grant: { type: Number, default: GRANT_PUBLIC, index: true },
  43. grantedUsers: [{ type: ObjectId, ref: 'User' }],
  44. grantedGroup: { type: ObjectId, ref: 'UserGroup', index: true },
  45. creator: { type: ObjectId, ref: 'User', index: true },
  46. lastUpdateUser: { type: ObjectId, ref: 'User' },
  47. liker: [{ type: ObjectId, ref: 'User' }],
  48. seenUsers: [{ type: ObjectId, ref: 'User' }],
  49. commentCount: { type: Number, default: 0 },
  50. slackChannels: { type: String },
  51. pageIdOnHackmd: String,
  52. revisionHackmdSynced: { type: ObjectId, ref: 'Revision' }, // the revision that is synced to HackMD
  53. hasDraftOnHackmd: { type: Boolean }, // set true if revision and revisionHackmdSynced are same but HackMD document has modified
  54. createdAt: { type: Date, default: Date.now },
  55. updatedAt: { type: Date, default: Date.now },
  56. deleteUser: { type: ObjectId, ref: 'User' },
  57. deletedAt: { type: Date },
  58. }, {
  59. toJSON: { getters: true },
  60. toObject: { getters: true },
  61. });
  62. // apply plugins
  63. pageSchema.plugin(mongoosePaginate);
  64. pageSchema.plugin(uniqueValidator);
  65. // TODO: test this after modifying Page.create
  66. // ensure v4 compatibility using partial index
  67. pageSchema.index({ path: 1 }, { unique: true, partialFilterExpression: { parent: null } });
  68. /**
  69. * return an array of ancestors paths that is extracted from specified pagePath
  70. * e.g.
  71. * when `pagePath` is `/foo/bar/baz`,
  72. * this method returns [`/foo/bar/baz`, `/foo/bar`, `/foo`, `/`]
  73. *
  74. * @param {string} pagePath
  75. * @return {string[]} ancestors paths
  76. */
  77. const extractToAncestorsPaths = (pagePath) => {
  78. const ancestorsPaths = [];
  79. let parentPath;
  80. while (parentPath !== '/') {
  81. parentPath = nodePath.dirname(parentPath || pagePath);
  82. ancestorsPaths.push(parentPath);
  83. }
  84. return ancestorsPaths;
  85. };
  86. /**
  87. * populate page (Query or Document) to show revision
  88. * @param {any} page Query or Document
  89. * @param {string} userPublicFields string to set to select
  90. */
  91. /* eslint-disable object-curly-newline, object-property-newline */
  92. const populateDataToShowRevision = (page, userPublicFields) => {
  93. return page
  94. .populate([
  95. { path: 'lastUpdateUser', model: 'User', select: userPublicFields },
  96. { path: 'creator', model: 'User', select: userPublicFields },
  97. { path: 'deleteUser', model: 'User', select: userPublicFields },
  98. { path: 'grantedGroup', model: 'UserGroup' },
  99. { path: 'revision', model: 'Revision', populate: {
  100. path: 'author', model: 'User', select: userPublicFields,
  101. } },
  102. ]);
  103. };
  104. /* eslint-enable object-curly-newline, object-property-newline */
  105. class PageQueryBuilder {
  106. constructor(query) {
  107. this.query = query;
  108. }
  109. addConditionToExcludeTrashed() {
  110. this.query = this.query
  111. .and({
  112. $or: [
  113. { status: null },
  114. { status: STATUS_PUBLISHED },
  115. ],
  116. });
  117. return this;
  118. }
  119. addConditionToExcludeRedirect() {
  120. this.query = this.query.and({ redirectTo: null });
  121. return this;
  122. }
  123. /**
  124. * generate the query to find the pages '{path}/*' and '{path}' self.
  125. * If top page, return without doing anything.
  126. */
  127. addConditionToListWithDescendants(path, option) {
  128. // No request is set for the top page
  129. if (isTopPage(path)) {
  130. return this;
  131. }
  132. const pathNormalized = pathUtils.normalizePath(path);
  133. const pathWithTrailingSlash = pathUtils.addTrailingSlash(path);
  134. const startsPattern = escapeStringRegexp(pathWithTrailingSlash);
  135. this.query = this.query
  136. .and({
  137. $or: [
  138. { path: pathNormalized },
  139. { path: new RegExp(`^${startsPattern}`) },
  140. ],
  141. });
  142. return this;
  143. }
  144. /**
  145. * generate the query to find the pages '{path}/*' (exclude '{path}' self).
  146. * If top page, return without doing anything.
  147. */
  148. addConditionToListOnlyDescendants(path, option) {
  149. // No request is set for the top page
  150. if (isTopPage(path)) {
  151. return this;
  152. }
  153. const pathWithTrailingSlash = pathUtils.addTrailingSlash(path);
  154. const startsPattern = escapeStringRegexp(pathWithTrailingSlash);
  155. this.query = this.query
  156. .and({ path: new RegExp(`^${startsPattern}`) });
  157. return this;
  158. }
  159. /**
  160. * generate the query to find pages that start with `path`
  161. *
  162. * In normal case, returns '{path}/*' and '{path}' self.
  163. * If top page, return without doing anything.
  164. *
  165. * *option*
  166. * Left for backward compatibility
  167. */
  168. addConditionToListByStartWith(path, option) {
  169. // No request is set for the top page
  170. if (isTopPage(path)) {
  171. return this;
  172. }
  173. const startsPattern = escapeStringRegexp(path);
  174. this.query = this.query
  175. .and({ path: new RegExp(`^${startsPattern}`) });
  176. return this;
  177. }
  178. addConditionToFilteringByViewer(user, userGroups, showAnyoneKnowsLink = false, showPagesRestrictedByOwner = false, showPagesRestrictedByGroup = false) {
  179. const grantConditions = [
  180. { grant: null },
  181. { grant: GRANT_PUBLIC },
  182. ];
  183. if (showAnyoneKnowsLink) {
  184. grantConditions.push({ grant: GRANT_RESTRICTED });
  185. }
  186. if (showPagesRestrictedByOwner) {
  187. grantConditions.push(
  188. { grant: GRANT_SPECIFIED },
  189. { grant: GRANT_OWNER },
  190. );
  191. }
  192. else if (user != null) {
  193. grantConditions.push(
  194. { grant: GRANT_SPECIFIED, grantedUsers: user._id },
  195. { grant: GRANT_OWNER, grantedUsers: user._id },
  196. );
  197. }
  198. if (showPagesRestrictedByGroup) {
  199. grantConditions.push(
  200. { grant: GRANT_USER_GROUP },
  201. );
  202. }
  203. else if (userGroups != null && userGroups.length > 0) {
  204. grantConditions.push(
  205. { grant: GRANT_USER_GROUP, grantedGroup: { $in: userGroups } },
  206. );
  207. }
  208. this.query = this.query
  209. .and({
  210. $or: grantConditions,
  211. });
  212. return this;
  213. }
  214. addConditionToPagenate(offset, limit, sortOpt) {
  215. this.query = this.query
  216. .sort(sortOpt).skip(offset).limit(limit); // eslint-disable-line newline-per-chained-call
  217. return this;
  218. }
  219. addConditionToListByPathsArray(paths) {
  220. this.query = this.query
  221. .and({
  222. path: {
  223. $in: paths,
  224. },
  225. });
  226. return this;
  227. }
  228. populateDataToList(userPublicFields) {
  229. this.query = this.query
  230. .populate({
  231. path: 'lastUpdateUser',
  232. select: userPublicFields,
  233. });
  234. return this;
  235. }
  236. populateDataToShowRevision(userPublicFields) {
  237. this.query = populateDataToShowRevision(this.query, userPublicFields);
  238. return this;
  239. }
  240. }
  241. module.exports = function(crowi) {
  242. let pageEvent;
  243. // init event
  244. if (crowi != null) {
  245. pageEvent = crowi.event('page');
  246. pageEvent.on('create', pageEvent.onCreate);
  247. pageEvent.on('update', pageEvent.onUpdate);
  248. pageEvent.on('createMany', pageEvent.onCreateMany);
  249. }
  250. function validateCrowi() {
  251. if (crowi == null) {
  252. throw new Error('"crowi" is null. Init User model with "crowi" argument first.');
  253. }
  254. }
  255. pageSchema.methods.isDeleted = function() {
  256. return (this.status === STATUS_DELETED) || isTrashPage(this.path);
  257. };
  258. pageSchema.methods.isPublic = function() {
  259. if (!this.grant || this.grant === GRANT_PUBLIC) {
  260. return true;
  261. }
  262. return false;
  263. };
  264. pageSchema.methods.isTopPage = function() {
  265. return isTopPage(this.path);
  266. };
  267. pageSchema.methods.isTemplate = function() {
  268. return checkTemplatePath(this.path);
  269. };
  270. pageSchema.methods.isLatestRevision = function() {
  271. // populate されていなくて判断できない
  272. if (!this.latestRevision || !this.revision) {
  273. return true;
  274. }
  275. // comparing ObjectId with string
  276. // eslint-disable-next-line eqeqeq
  277. return (this.latestRevision == this.revision._id.toString());
  278. };
  279. pageSchema.methods.findRelatedTagsById = async function() {
  280. const PageTagRelation = mongoose.model('PageTagRelation');
  281. const relations = await PageTagRelation.find({ relatedPage: this._id }).populate('relatedTag');
  282. return relations.map((relation) => { return relation.relatedTag.name });
  283. };
  284. pageSchema.methods.isUpdatable = function(previousRevision) {
  285. const revision = this.latestRevision || this.revision;
  286. // comparing ObjectId with string
  287. // eslint-disable-next-line eqeqeq
  288. if (revision != previousRevision) {
  289. return false;
  290. }
  291. return true;
  292. };
  293. pageSchema.methods.isLiked = function(user) {
  294. if (user == null || user._id == null) {
  295. return false;
  296. }
  297. return this.liker.some((likedUserId) => {
  298. return likedUserId.toString() === user._id.toString();
  299. });
  300. };
  301. pageSchema.methods.like = function(userData) {
  302. const self = this;
  303. return new Promise(((resolve, reject) => {
  304. const added = self.liker.addToSet(userData._id);
  305. if (added.length > 0) {
  306. self.save((err, data) => {
  307. if (err) {
  308. return reject(err);
  309. }
  310. logger.debug('liker updated!', added);
  311. return resolve(data);
  312. });
  313. }
  314. else {
  315. logger.debug('liker not updated');
  316. return reject(self);
  317. }
  318. }));
  319. };
  320. pageSchema.methods.unlike = function(userData, callback) {
  321. const self = this;
  322. return new Promise(((resolve, reject) => {
  323. const beforeCount = self.liker.length;
  324. self.liker.pull(userData._id);
  325. if (self.liker.length !== beforeCount) {
  326. self.save((err, data) => {
  327. if (err) {
  328. return reject(err);
  329. }
  330. return resolve(data);
  331. });
  332. }
  333. else {
  334. logger.debug('liker not updated');
  335. return reject(self);
  336. }
  337. }));
  338. };
  339. pageSchema.methods.isSeenUser = function(userData) {
  340. return this.seenUsers.includes(userData._id);
  341. };
  342. pageSchema.methods.seen = async function(userData) {
  343. if (this.isSeenUser(userData)) {
  344. debug('seenUsers not updated');
  345. return this;
  346. }
  347. if (!userData || !userData._id) {
  348. throw new Error('User data is not valid');
  349. }
  350. const added = this.seenUsers.addToSet(userData._id);
  351. const saved = await this.save();
  352. debug('seenUsers updated!', added);
  353. return saved;
  354. };
  355. pageSchema.methods.updateSlackChannels = function(slackChannels) {
  356. this.slackChannels = slackChannels;
  357. return this.save();
  358. };
  359. pageSchema.methods.initLatestRevisionField = async function(revisionId) {
  360. this.latestRevision = this.revision;
  361. if (revisionId != null) {
  362. this.revision = revisionId;
  363. }
  364. };
  365. pageSchema.methods.populateDataToShowRevision = async function() {
  366. validateCrowi();
  367. const User = crowi.model('User');
  368. return populateDataToShowRevision(this, User.USER_FIELDS_EXCEPT_CONFIDENTIAL)
  369. .execPopulate();
  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').execPopulate();
  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.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().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. const generateAncestorPaths = (path, ancestorPaths = []) => {
  785. const parentPath = nodePath.dirname(path);
  786. ancestorPaths.push(parentPath);
  787. if (path !== '/') return generateAncestorPaths(parentPath, ancestorPaths);
  788. return ancestorPaths;
  789. };
  790. pageSchema.statics.createEmptyPagesByPaths = async function(paths) {
  791. const Page = this;
  792. // find existing parents
  793. const builder = new PageQueryBuilder(Page.find({}, { _id: 0, path: 1 }));
  794. const existingPages = await builder
  795. .addConditionToListByPathsArray(paths)
  796. .query
  797. .lean()
  798. .exec();
  799. const existingPagePaths = existingPages.map(page => page.path);
  800. // paths to create empty pages
  801. const notExistingPagePaths = paths.filter(path => !existingPagePaths.includes(path));
  802. // insertMany empty pages
  803. try {
  804. await Page.insertMany(notExistingPagePaths.map(path => ({ path, isEmpty: true })));
  805. }
  806. catch (err) {
  807. logger.error('Failed to insert empty pages.', err);
  808. throw err;
  809. }
  810. };
  811. pageSchema.statics._getParentIdAndFillAncestors = async function(path) {
  812. const Page = this;
  813. const parentPath = nodePath.dirname(path);
  814. const parent = await Page.findOne({ path: parentPath }); // find the oldest parent which must always be the true parent
  815. if (parent != null) { // fill parents if parent is null
  816. return parent._id;
  817. }
  818. const ancestorPaths = generateAncestorPaths(path); // paths of parents need to be created
  819. // just create ancestors with empty pages
  820. await Page.createEmptyPagesByPaths(ancestorPaths);
  821. // find ancestors
  822. const builder = new PageQueryBuilder(Page.find({}, { _id: 1, path: 1 }));
  823. const ancestors = await builder
  824. .addConditionToListByPathsArray(ancestorPaths)
  825. .query
  826. .lean()
  827. .exec();
  828. const ancestorsMap = new Map(); // Map<path, _id>
  829. ancestors.forEach(page => ancestorsMap.set(page.path, page._id));
  830. // bulkWrite to update ancestors
  831. const nonRootAncestors = ancestors.filter(page => page.path !== '/');
  832. const operations = nonRootAncestors.map((page) => {
  833. const { path } = page;
  834. const parentPath = nodePath.dirname(path);
  835. return {
  836. updateOne: {
  837. filter: {
  838. path,
  839. },
  840. update: {
  841. parent: ancestorsMap.get(parentPath),
  842. },
  843. },
  844. };
  845. });
  846. await Page.bulkWrite(operations);
  847. const parentId = ancestorsMap.get(parentPath);
  848. return parentId;
  849. };
  850. pageSchema.statics.create = async function(path, body, user, options = {}) {
  851. validateCrowi();
  852. const Page = this;
  853. const isV5Compatible = crowi.configManager.getConfig('crowi', 'app:isV5Compatible');
  854. const Revision = crowi.model('Revision');
  855. const {
  856. format = 'markdown', redirectTo, grantUserGroupId, parentId,
  857. } = options;
  858. // sanitize path
  859. path = crowi.xss.process(path); // eslint-disable-line no-param-reassign
  860. let grant = options.grant;
  861. // force public
  862. if (isTopPage(path)) {
  863. grant = GRANT_PUBLIC;
  864. }
  865. /*
  866. * v4 compatible
  867. */
  868. let parent = parentId;
  869. if (!isV5Compatible) {
  870. const isExist = await this.count({ path });
  871. if (isExist) {
  872. throw new Error('Cannot create new page to existed path');
  873. }
  874. }
  875. if (isV5Compatible && parentId == null) {
  876. // fill parent before saving the page
  877. parent = await Page._getParentIdAndFillAncestors(path);
  878. }
  879. const page = new Page();
  880. page.path = path;
  881. page.creator = user;
  882. page.lastUpdateUser = user;
  883. page.redirectTo = redirectTo;
  884. page.status = STATUS_PUBLISHED;
  885. page.parent = parent;
  886. await validateAppliedScope(user, grant, grantUserGroupId);
  887. page.applyScope(user, grant, grantUserGroupId);
  888. let savedPage = await page.save();
  889. const newRevision = Revision.prepareRevision(savedPage, body, null, user, { format });
  890. const revision = await pushRevision(savedPage, newRevision, user);
  891. savedPage = await this.findByPath(revision.path);
  892. await savedPage.populateDataToShowRevision();
  893. pageEvent.emit('create', savedPage, user);
  894. return savedPage;
  895. };
  896. pageSchema.statics.updatePage = async function(pageData, body, previousBody, user, options = {}) {
  897. validateCrowi();
  898. const Revision = crowi.model('Revision');
  899. const grant = options.grant || pageData.grant; // use the previous data if absence
  900. const grantUserGroupId = options.grantUserGroupId || pageData.grantUserGroupId; // use the previous data if absence
  901. const isSyncRevisionToHackmd = options.isSyncRevisionToHackmd;
  902. await validateAppliedScope(user, grant, grantUserGroupId);
  903. pageData.applyScope(user, grant, grantUserGroupId);
  904. // update existing page
  905. let savedPage = await pageData.save();
  906. const newRevision = await Revision.prepareRevision(pageData, body, previousBody, user);
  907. const revision = await pushRevision(savedPage, newRevision, user);
  908. savedPage = await this.findByPath(revision.path);
  909. await savedPage.populateDataToShowRevision();
  910. if (isSyncRevisionToHackmd) {
  911. savedPage = await this.syncRevisionToHackmd(savedPage);
  912. }
  913. pageEvent.emit('update', savedPage, user);
  914. return savedPage;
  915. };
  916. pageSchema.statics.applyScopesToDescendantsAsyncronously = async function(parentPage, user) {
  917. const builder = new PageQueryBuilder(this.find());
  918. builder.addConditionToListWithDescendants(parentPage.path);
  919. builder.addConditionToExcludeRedirect();
  920. // add grant conditions
  921. await addConditionToFilteringByViewerToEdit(builder, user);
  922. // get all pages that the specified user can update
  923. const pages = await builder.query.exec();
  924. for (const page of pages) {
  925. // skip parentPage
  926. if (page.id === parentPage.id) {
  927. continue;
  928. }
  929. page.applyScope(user, parentPage.grant, parentPage.grantedGroup);
  930. page.save();
  931. }
  932. };
  933. pageSchema.statics.removeByPath = function(path) {
  934. if (path == null) {
  935. throw new Error('path is required');
  936. }
  937. return this.findOneAndRemove({ path }).exec();
  938. };
  939. /**
  940. * remove the page that is redirecting to specified `pagePath` recursively
  941. * ex: when
  942. * '/page1' redirects to '/page2' and
  943. * '/page2' redirects to '/page3'
  944. * and given '/page3',
  945. * '/page1' and '/page2' will be removed
  946. *
  947. * @param {string} pagePath
  948. */
  949. pageSchema.statics.removeRedirectOriginPageByPath = async function(pagePath) {
  950. const redirectPage = await this.findByRedirectTo(pagePath);
  951. if (redirectPage == null) {
  952. return;
  953. }
  954. // remove
  955. await this.findByIdAndRemove(redirectPage.id);
  956. // remove recursive
  957. await this.removeRedirectOriginPageByPath(redirectPage.path);
  958. };
  959. pageSchema.statics.findListByPathsArray = async function(paths) {
  960. const queryBuilder = new PageQueryBuilder(this.find());
  961. queryBuilder.addConditionToListByPathsArray(paths);
  962. return await queryBuilder.query.exec();
  963. };
  964. pageSchema.statics.publicizePage = async function(page) {
  965. page.grantedGroup = null;
  966. page.grant = GRANT_PUBLIC;
  967. await page.save();
  968. };
  969. pageSchema.statics.transferPageToGroup = async function(page, transferToUserGroupId) {
  970. const UserGroup = mongoose.model('UserGroup');
  971. // check page existence
  972. const isExist = await UserGroup.count({ _id: transferToUserGroupId }) > 0;
  973. if (isExist) {
  974. page.grantedGroup = transferToUserGroupId;
  975. await page.save();
  976. }
  977. else {
  978. throw new Error('Cannot find the group to which private pages belong to. _id: ', transferToUserGroupId);
  979. }
  980. };
  981. /**
  982. * associate GROWI page and HackMD page
  983. * @param {Page} pageData
  984. * @param {string} pageIdOnHackmd
  985. */
  986. pageSchema.statics.registerHackmdPage = function(pageData, pageIdOnHackmd) {
  987. pageData.pageIdOnHackmd = pageIdOnHackmd;
  988. return this.syncRevisionToHackmd(pageData);
  989. };
  990. /**
  991. * update revisionHackmdSynced
  992. * @param {Page} pageData
  993. * @param {bool} isSave whether save or not
  994. */
  995. pageSchema.statics.syncRevisionToHackmd = function(pageData, isSave = true) {
  996. pageData.revisionHackmdSynced = pageData.revision;
  997. pageData.hasDraftOnHackmd = false;
  998. let returnData = pageData;
  999. if (isSave) {
  1000. returnData = pageData.save();
  1001. }
  1002. return returnData;
  1003. };
  1004. /**
  1005. * update hasDraftOnHackmd
  1006. * !! This will be invoked many time from many people !!
  1007. *
  1008. * @param {Page} pageData
  1009. * @param {Boolean} newValue
  1010. */
  1011. pageSchema.statics.updateHasDraftOnHackmd = async function(pageData, newValue) {
  1012. if (pageData.hasDraftOnHackmd === newValue) {
  1013. // do nothing when hasDraftOnHackmd equals to newValue
  1014. return;
  1015. }
  1016. pageData.hasDraftOnHackmd = newValue;
  1017. return pageData.save();
  1018. };
  1019. pageSchema.statics.getHistories = function() {
  1020. // TODO
  1021. };
  1022. pageSchema.statics.STATUS_PUBLISHED = STATUS_PUBLISHED;
  1023. pageSchema.statics.STATUS_DELETED = STATUS_DELETED;
  1024. pageSchema.statics.GRANT_PUBLIC = GRANT_PUBLIC;
  1025. pageSchema.statics.GRANT_RESTRICTED = GRANT_RESTRICTED;
  1026. pageSchema.statics.GRANT_SPECIFIED = GRANT_SPECIFIED;
  1027. pageSchema.statics.GRANT_OWNER = GRANT_OWNER;
  1028. pageSchema.statics.GRANT_USER_GROUP = GRANT_USER_GROUP;
  1029. pageSchema.statics.PAGE_GRANT_ERROR = PAGE_GRANT_ERROR;
  1030. pageSchema.statics.PageQueryBuilder = PageQueryBuilder;
  1031. return mongoose.model('Page', pageSchema);
  1032. };