page.js 34 KB

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