page.js 34 KB

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