page.js 37 KB

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