page.js 34 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171
  1. import { templateChecker, pagePathUtils } from '@growi/core';
  2. import loggerFactory from '~/utils/logger';
  3. // disable no-return-await for model functions
  4. /* eslint-disable no-return-await */
  5. /* eslint-disable no-use-before-define */
  6. const debug = require('debug')('growi:models:page');
  7. const nodePath = require('path');
  8. const urljoin = require('url-join');
  9. const mongoose = require('mongoose');
  10. const mongoosePaginate = require('mongoose-paginate-v2');
  11. const uniqueValidator = require('mongoose-unique-validator');
  12. const differenceInYears = require('date-fns/differenceInYears');
  13. const { pathUtils } = require('growi-commons');
  14. const escapeStringRegexp = require('escape-string-regexp');
  15. const { isTopPage, isTrashPage } = pagePathUtils;
  16. const { checkTemplatePath } = templateChecker;
  17. const logger = loggerFactory('growi:models:page');
  18. const ObjectId = mongoose.Schema.Types.ObjectId;
  19. /*
  20. * define schema
  21. */
  22. const GRANT_PUBLIC = 1;
  23. const GRANT_RESTRICTED = 2;
  24. const GRANT_SPECIFIED = 3;
  25. const GRANT_OWNER = 4;
  26. const GRANT_USER_GROUP = 5;
  27. const PAGE_GRANT_ERROR = 1;
  28. const STATUS_PUBLISHED = 'published';
  29. const STATUS_DELETED = 'deleted';
  30. const pageSchema = new mongoose.Schema({
  31. path: {
  32. type: String, required: true, index: true, unique: true,
  33. },
  34. revision: { type: ObjectId, ref: 'Revision' },
  35. redirectTo: { type: String, index: true },
  36. status: { type: String, default: STATUS_PUBLISHED, index: true },
  37. grant: { type: Number, default: GRANT_PUBLIC, index: true },
  38. grantedUsers: [{ type: ObjectId, ref: 'User' }],
  39. grantedGroup: { type: ObjectId, ref: 'UserGroup', index: true },
  40. creator: { type: ObjectId, ref: 'User', index: true },
  41. lastUpdateUser: { type: ObjectId, ref: 'User' },
  42. liker: [{ type: ObjectId, ref: 'User' }],
  43. seenUsers: [{ type: ObjectId, ref: 'User' }],
  44. commentCount: { type: Number, default: 0 },
  45. slackChannels: { type: String },
  46. pageIdOnHackmd: String,
  47. revisionHackmdSynced: { type: ObjectId, ref: 'Revision' }, // the revision that is synced to HackMD
  48. hasDraftOnHackmd: { type: Boolean }, // set true if revision and revisionHackmdSynced are same but HackMD document has modified
  49. createdAt: { type: Date, default: Date.now },
  50. updatedAt: { type: Date, default: Date.now },
  51. deleteUser: { type: ObjectId, ref: 'User' },
  52. deletedAt: { type: Date },
  53. }, {
  54. toJSON: { getters: true },
  55. toObject: { getters: true },
  56. });
  57. // apply plugins
  58. pageSchema.plugin(mongoosePaginate);
  59. pageSchema.plugin(uniqueValidator);
  60. /**
  61. * return an array of ancestors paths that is extracted from specified pagePath
  62. * e.g.
  63. * when `pagePath` is `/foo/bar/baz`,
  64. * this method returns [`/foo/bar/baz`, `/foo/bar`, `/foo`, `/`]
  65. *
  66. * @param {string} pagePath
  67. * @return {string[]} ancestors paths
  68. */
  69. const extractToAncestorsPaths = (pagePath) => {
  70. const ancestorsPaths = [];
  71. let parentPath;
  72. while (parentPath !== '/') {
  73. parentPath = nodePath.dirname(parentPath || pagePath);
  74. ancestorsPaths.push(parentPath);
  75. }
  76. return ancestorsPaths;
  77. };
  78. /**
  79. * populate page (Query or Document) to show revision
  80. * @param {any} page Query or Document
  81. * @param {string} userPublicFields string to set to select
  82. */
  83. /* eslint-disable object-curly-newline, object-property-newline */
  84. const populateDataToShowRevision = (page, userPublicFields) => {
  85. return page
  86. .populate([
  87. { path: 'lastUpdateUser', model: 'User', select: userPublicFields },
  88. { path: 'creator', model: 'User', select: userPublicFields },
  89. { path: 'deleteUser', model: 'User', select: userPublicFields },
  90. { path: 'grantedGroup', model: 'UserGroup' },
  91. { path: 'revision', model: 'Revision', populate: {
  92. path: 'author', model: 'User', select: userPublicFields,
  93. } },
  94. ]);
  95. };
  96. /* eslint-enable object-curly-newline, object-property-newline */
  97. class PageQueryBuilder {
  98. constructor(query) {
  99. this.query = query;
  100. }
  101. addConditionToExcludeTrashed() {
  102. this.query = this.query
  103. .and({
  104. $or: [
  105. { status: null },
  106. { status: STATUS_PUBLISHED },
  107. ],
  108. });
  109. return this;
  110. }
  111. addConditionToExcludeRedirect() {
  112. this.query = this.query.and({ redirectTo: null });
  113. return this;
  114. }
  115. /**
  116. * generate the query to find the pages '{path}/*' and '{path}' self.
  117. * If top page, return without doing anything.
  118. */
  119. addConditionToListWithDescendants(path, option) {
  120. // No request is set for the top page
  121. if (isTopPage(path)) {
  122. return this;
  123. }
  124. const pathNormalized = pathUtils.normalizePath(path);
  125. const pathWithTrailingSlash = pathUtils.addTrailingSlash(path);
  126. const startsPattern = escapeStringRegexp(pathWithTrailingSlash);
  127. this.query = this.query
  128. .and({
  129. $or: [
  130. { path: pathNormalized },
  131. { path: new RegExp(`^${startsPattern}`) },
  132. ],
  133. });
  134. return this;
  135. }
  136. /**
  137. * generate the query to find the pages '{path}/*' (exclude '{path}' self).
  138. * If top page, return without doing anything.
  139. */
  140. addConditionToListOnlyDescendants(path, option) {
  141. // No request is set for the top page
  142. if (isTopPage(path)) {
  143. return this;
  144. }
  145. const pathWithTrailingSlash = pathUtils.addTrailingSlash(path);
  146. const startsPattern = escapeStringRegexp(pathWithTrailingSlash);
  147. this.query = this.query
  148. .and({ path: new RegExp(`^${startsPattern}`) });
  149. return this;
  150. }
  151. /**
  152. * generate the query to find pages that start with `path`
  153. *
  154. * In normal case, returns '{path}/*' and '{path}' self.
  155. * If top page, return without doing anything.
  156. *
  157. * *option*
  158. * Left for backward compatibility
  159. */
  160. addConditionToListByStartWith(path, option) {
  161. // No request is set for the top page
  162. if (isTopPage(path)) {
  163. return this;
  164. }
  165. const startsPattern = escapeStringRegexp(path);
  166. this.query = this.query
  167. .and({ path: new RegExp(`^${startsPattern}`) });
  168. return this;
  169. }
  170. addConditionToFilteringByViewer(user, userGroups, showAnyoneKnowsLink = false, showPagesRestrictedByOwner = false, showPagesRestrictedByGroup = false) {
  171. const grantConditions = [
  172. { grant: null },
  173. { grant: GRANT_PUBLIC },
  174. ];
  175. if (showAnyoneKnowsLink) {
  176. grantConditions.push({ grant: GRANT_RESTRICTED });
  177. }
  178. if (showPagesRestrictedByOwner) {
  179. grantConditions.push(
  180. { grant: GRANT_SPECIFIED },
  181. { grant: GRANT_OWNER },
  182. );
  183. }
  184. else if (user != null) {
  185. grantConditions.push(
  186. { grant: GRANT_SPECIFIED, grantedUsers: user._id },
  187. { grant: GRANT_OWNER, grantedUsers: user._id },
  188. );
  189. }
  190. if (showPagesRestrictedByGroup) {
  191. grantConditions.push(
  192. { grant: GRANT_USER_GROUP },
  193. );
  194. }
  195. else if (userGroups != null && userGroups.length > 0) {
  196. grantConditions.push(
  197. { grant: GRANT_USER_GROUP, grantedGroup: { $in: userGroups } },
  198. );
  199. }
  200. this.query = this.query
  201. .and({
  202. $or: grantConditions,
  203. });
  204. return this;
  205. }
  206. addConditionToPagenate(offset, limit, sortOpt) {
  207. this.query = this.query
  208. .sort(sortOpt).skip(offset).limit(limit); // eslint-disable-line newline-per-chained-call
  209. return this;
  210. }
  211. addConditionToListByPathsArray(paths) {
  212. this.query = this.query
  213. .and({
  214. path: {
  215. $in: paths,
  216. },
  217. });
  218. return this;
  219. }
  220. populateDataToList(userPublicFields) {
  221. this.query = this.query
  222. .populate({
  223. path: 'lastUpdateUser',
  224. select: userPublicFields,
  225. });
  226. return this;
  227. }
  228. populateDataToShowRevision(userPublicFields) {
  229. this.query = populateDataToShowRevision(this.query, userPublicFields);
  230. return this;
  231. }
  232. }
  233. module.exports = function(crowi) {
  234. let pageEvent;
  235. // init event
  236. if (crowi != null) {
  237. pageEvent = crowi.event('page');
  238. pageEvent.on('create', pageEvent.onCreate);
  239. pageEvent.on('update', pageEvent.onUpdate);
  240. pageEvent.on('createMany', pageEvent.onCreateMany);
  241. }
  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.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. const socketClientId = options.socketClientId || null;
  784. // sanitize path
  785. path = crowi.xss.process(path); // eslint-disable-line no-param-reassign
  786. let grant = options.grant;
  787. // force public
  788. if (isTopPage(path)) {
  789. grant = GRANT_PUBLIC;
  790. }
  791. const isExist = await this.count({ path });
  792. if (isExist) {
  793. throw new Error('Cannot create new page to existed path');
  794. }
  795. const page = new Page();
  796. page.path = path;
  797. page.creator = user;
  798. page.lastUpdateUser = user;
  799. page.redirectTo = redirectTo;
  800. page.status = STATUS_PUBLISHED;
  801. await validateAppliedScope(user, grant, grantUserGroupId);
  802. page.applyScope(user, grant, grantUserGroupId);
  803. let savedPage = await page.save();
  804. const newRevision = Revision.prepareRevision(savedPage, body, null, user, { format });
  805. const revision = await pushRevision(savedPage, newRevision, user);
  806. savedPage = await this.findByPath(revision.path);
  807. await savedPage.populateDataToShowRevision();
  808. pageEvent.emit('create', savedPage, user, socketClientId);
  809. return savedPage;
  810. };
  811. pageSchema.statics.updatePage = async function(pageData, body, previousBody, user, options = {}) {
  812. validateCrowi();
  813. const Revision = crowi.model('Revision');
  814. const grant = options.grant || pageData.grant; // use the previous data if absence
  815. const grantUserGroupId = options.grantUserGroupId || pageData.grantUserGroupId; // use the previous data if absence
  816. const isSyncRevisionToHackmd = options.isSyncRevisionToHackmd;
  817. const socketClientId = options.socketClientId || null;
  818. await validateAppliedScope(user, grant, grantUserGroupId);
  819. pageData.applyScope(user, grant, grantUserGroupId);
  820. // update existing page
  821. let savedPage = await pageData.save();
  822. const newRevision = await Revision.prepareRevision(pageData, body, previousBody, user);
  823. const revision = await pushRevision(savedPage, newRevision, user);
  824. savedPage = await this.findByPath(revision.path);
  825. await savedPage.populateDataToShowRevision();
  826. if (isSyncRevisionToHackmd) {
  827. savedPage = await this.syncRevisionToHackmd(savedPage);
  828. }
  829. pageEvent.emit('update', savedPage, user, socketClientId);
  830. return savedPage;
  831. };
  832. pageSchema.statics.applyScopesToDescendantsAsyncronously = async function(parentPage, user) {
  833. const builder = new PageQueryBuilder(this.find());
  834. builder.addConditionToListWithDescendants(parentPage.path);
  835. builder.addConditionToExcludeRedirect();
  836. // add grant conditions
  837. await addConditionToFilteringByViewerToEdit(builder, user);
  838. // get all pages that the specified user can update
  839. const pages = await builder.query.exec();
  840. for (const page of pages) {
  841. // skip parentPage
  842. if (page.id === parentPage.id) {
  843. continue;
  844. }
  845. page.applyScope(user, parentPage.grant, parentPage.grantedGroup);
  846. page.save();
  847. }
  848. };
  849. pageSchema.statics.removeByPath = function(path) {
  850. if (path == null) {
  851. throw new Error('path is required');
  852. }
  853. return this.findOneAndRemove({ path }).exec();
  854. };
  855. /**
  856. * remove the page that is redirecting to specified `pagePath` recursively
  857. * ex: when
  858. * '/page1' redirects to '/page2' and
  859. * '/page2' redirects to '/page3'
  860. * and given '/page3',
  861. * '/page1' and '/page2' will be removed
  862. *
  863. * @param {string} pagePath
  864. */
  865. pageSchema.statics.removeRedirectOriginPageByPath = async function(pagePath) {
  866. const redirectPage = await this.findByRedirectTo(pagePath);
  867. if (redirectPage == null) {
  868. return;
  869. }
  870. // remove
  871. await this.findByIdAndRemove(redirectPage.id);
  872. // remove recursive
  873. await this.removeRedirectOriginPageByPath(redirectPage.path);
  874. };
  875. pageSchema.statics.findListByPathsArray = async function(paths) {
  876. const queryBuilder = new PageQueryBuilder(this.find());
  877. queryBuilder.addConditionToListByPathsArray(paths);
  878. return await queryBuilder.query.exec();
  879. };
  880. pageSchema.statics.publicizePage = async function(page) {
  881. page.grantedGroup = null;
  882. page.grant = GRANT_PUBLIC;
  883. await page.save();
  884. };
  885. pageSchema.statics.transferPageToGroup = async function(page, transferToUserGroupId) {
  886. const UserGroup = mongoose.model('UserGroup');
  887. // check page existence
  888. const isExist = await UserGroup.count({ _id: transferToUserGroupId }) > 0;
  889. if (isExist) {
  890. page.grantedGroup = transferToUserGroupId;
  891. await page.save();
  892. }
  893. else {
  894. throw new Error('Cannot find the group to which private pages belong to. _id: ', transferToUserGroupId);
  895. }
  896. };
  897. /**
  898. * associate GROWI page and HackMD page
  899. * @param {Page} pageData
  900. * @param {string} pageIdOnHackmd
  901. */
  902. pageSchema.statics.registerHackmdPage = function(pageData, pageIdOnHackmd) {
  903. pageData.pageIdOnHackmd = pageIdOnHackmd;
  904. return this.syncRevisionToHackmd(pageData);
  905. };
  906. /**
  907. * update revisionHackmdSynced
  908. * @param {Page} pageData
  909. * @param {bool} isSave whether save or not
  910. */
  911. pageSchema.statics.syncRevisionToHackmd = function(pageData, isSave = true) {
  912. pageData.revisionHackmdSynced = pageData.revision;
  913. pageData.hasDraftOnHackmd = false;
  914. let returnData = pageData;
  915. if (isSave) {
  916. returnData = pageData.save();
  917. }
  918. return returnData;
  919. };
  920. /**
  921. * update hasDraftOnHackmd
  922. * !! This will be invoked many time from many people !!
  923. *
  924. * @param {Page} pageData
  925. * @param {Boolean} newValue
  926. */
  927. pageSchema.statics.updateHasDraftOnHackmd = async function(pageData, newValue) {
  928. if (pageData.hasDraftOnHackmd === newValue) {
  929. // do nothing when hasDraftOnHackmd equals to newValue
  930. return;
  931. }
  932. pageData.hasDraftOnHackmd = newValue;
  933. return pageData.save();
  934. };
  935. pageSchema.statics.getHistories = function() {
  936. // TODO
  937. };
  938. pageSchema.statics.STATUS_PUBLISHED = STATUS_PUBLISHED;
  939. pageSchema.statics.STATUS_DELETED = STATUS_DELETED;
  940. pageSchema.statics.GRANT_PUBLIC = GRANT_PUBLIC;
  941. pageSchema.statics.GRANT_RESTRICTED = GRANT_RESTRICTED;
  942. pageSchema.statics.GRANT_SPECIFIED = GRANT_SPECIFIED;
  943. pageSchema.statics.GRANT_OWNER = GRANT_OWNER;
  944. pageSchema.statics.GRANT_USER_GROUP = GRANT_USER_GROUP;
  945. pageSchema.statics.PAGE_GRANT_ERROR = PAGE_GRANT_ERROR;
  946. pageSchema.statics.PageQueryBuilder = PageQueryBuilder;
  947. return mongoose.model('Page', pageSchema);
  948. };