page.js 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164
  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.fixToCreatableName = function(path) {
  433. return path
  434. .replace(/\/\//g, '/');
  435. };
  436. pageSchema.statics.updateRevision = function(pageId, revisionId, cb) {
  437. this.update({ _id: pageId }, { revision: revisionId }, {}, (err, data) => {
  438. cb(err, data);
  439. });
  440. };
  441. /**
  442. * return whether the user is accessible to the page
  443. * @param {string} id ObjectId
  444. * @param {User} user
  445. */
  446. pageSchema.statics.isAccessiblePageByViewer = async function(id, user) {
  447. const baseQuery = this.count({ _id: id });
  448. let userGroups = [];
  449. if (user != null) {
  450. validateCrowi();
  451. const UserGroupRelation = crowi.model('UserGroupRelation');
  452. userGroups = await UserGroupRelation.findAllUserGroupIdsRelatedToUser(user);
  453. }
  454. const queryBuilder = new PageQueryBuilder(baseQuery);
  455. queryBuilder.addConditionToFilteringByViewer(user, userGroups, true);
  456. const count = await queryBuilder.query.exec();
  457. return count > 0;
  458. };
  459. /**
  460. * @param {string} id ObjectId
  461. * @param {User} user User instance
  462. * @param {UserGroup[]} userGroups List of UserGroup instances
  463. */
  464. pageSchema.statics.findByIdAndViewer = async function(id, user, userGroups) {
  465. const baseQuery = this.findOne({ _id: id });
  466. let relatedUserGroups = userGroups;
  467. if (user != null && relatedUserGroups == null) {
  468. validateCrowi();
  469. const UserGroupRelation = crowi.model('UserGroupRelation');
  470. relatedUserGroups = await UserGroupRelation.findAllUserGroupIdsRelatedToUser(user);
  471. }
  472. const queryBuilder = new PageQueryBuilder(baseQuery);
  473. queryBuilder.addConditionToFilteringByViewer(user, relatedUserGroups, true);
  474. return await queryBuilder.query.exec();
  475. };
  476. // find page by path
  477. pageSchema.statics.findByPath = function(path) {
  478. if (path == null) {
  479. return null;
  480. }
  481. return this.findOne({ path });
  482. };
  483. /**
  484. * @param {string} path Page path
  485. * @param {User} user User instance
  486. * @param {UserGroup[]} userGroups List of UserGroup instances
  487. */
  488. pageSchema.statics.findByPathAndViewer = async function(path, user, userGroups) {
  489. if (path == null) {
  490. throw new Error('path is required.');
  491. }
  492. const baseQuery = this.findOne({ path });
  493. let relatedUserGroups = userGroups;
  494. if (user != null && relatedUserGroups == null) {
  495. validateCrowi();
  496. const UserGroupRelation = crowi.model('UserGroupRelation');
  497. relatedUserGroups = await UserGroupRelation.findAllUserGroupIdsRelatedToUser(user);
  498. }
  499. const queryBuilder = new PageQueryBuilder(baseQuery);
  500. queryBuilder.addConditionToFilteringByViewer(user, relatedUserGroups, true);
  501. return await queryBuilder.query.exec();
  502. };
  503. /**
  504. * @param {string} path Page path
  505. * @param {User} user User instance
  506. * @param {UserGroup[]} userGroups List of UserGroup instances
  507. */
  508. pageSchema.statics.findAncestorByPathAndViewer = async function(path, user, userGroups) {
  509. if (path == null) {
  510. throw new Error('path is required.');
  511. }
  512. if (path === '/') {
  513. return null;
  514. }
  515. const ancestorsPaths = extractToAncestorsPaths(path);
  516. // pick the longest one
  517. const baseQuery = this.findOne({ path: { $in: ancestorsPaths } }).sort({ path: -1 });
  518. let relatedUserGroups = userGroups;
  519. if (user != null && relatedUserGroups == null) {
  520. validateCrowi();
  521. const UserGroupRelation = crowi.model('UserGroupRelation');
  522. relatedUserGroups = await UserGroupRelation.findAllUserGroupIdsRelatedToUser(user);
  523. }
  524. const queryBuilder = new PageQueryBuilder(baseQuery);
  525. queryBuilder.addConditionToFilteringByViewer(user, relatedUserGroups);
  526. return await queryBuilder.query.exec();
  527. };
  528. pageSchema.statics.findByRedirectTo = function(path) {
  529. return this.findOne({ redirectTo: path });
  530. };
  531. /**
  532. * find pages that is match with `path` and its descendants
  533. */
  534. pageSchema.statics.findListWithDescendants = async function(path, user, option = {}) {
  535. const builder = new PageQueryBuilder(this.find());
  536. builder.addConditionToListWithDescendants(path, option);
  537. return await findListFromBuilderAndViewer(builder, user, false, option);
  538. };
  539. /**
  540. * find pages that is match with `path` and its descendants whitch user is able to manage
  541. */
  542. pageSchema.statics.findManageableListWithDescendants = async function(page, user, option = {}) {
  543. if (user == null) {
  544. return null;
  545. }
  546. const builder = new PageQueryBuilder(this.find());
  547. builder.addConditionToListWithDescendants(page.path, option);
  548. builder.addConditionToExcludeRedirect();
  549. // add grant conditions
  550. await addConditionToFilteringByViewerToEdit(builder, user);
  551. const { pages } = await findListFromBuilderAndViewer(builder, user, false, option);
  552. // add page if 'grant' is GRANT_RESTRICTED
  553. // because addConditionToListWithDescendants excludes GRANT_RESTRICTED pages
  554. if (page.grant === GRANT_RESTRICTED) {
  555. pages.push(page);
  556. }
  557. return pages;
  558. };
  559. /**
  560. * find pages that start with `path`
  561. */
  562. pageSchema.statics.findListByStartWith = async function(path, user, option) {
  563. const builder = new PageQueryBuilder(this.find());
  564. builder.addConditionToListByStartWith(path, option);
  565. return await findListFromBuilderAndViewer(builder, user, false, option);
  566. };
  567. /**
  568. * find pages that is created by targetUser
  569. *
  570. * @param {User} targetUser
  571. * @param {User} currentUser
  572. * @param {any} option
  573. */
  574. pageSchema.statics.findListByCreator = async function(targetUser, currentUser, option) {
  575. const opt = Object.assign({ sort: 'createdAt', desc: -1 }, option);
  576. const builder = new PageQueryBuilder(this.find({ creator: targetUser._id }));
  577. let showAnyoneKnowsLink = null;
  578. if (targetUser != null && currentUser != null) {
  579. showAnyoneKnowsLink = targetUser._id.equals(currentUser._id);
  580. }
  581. return await findListFromBuilderAndViewer(builder, currentUser, showAnyoneKnowsLink, opt);
  582. };
  583. pageSchema.statics.findListByPageIds = async function(ids, option) {
  584. const User = crowi.model('User');
  585. const opt = Object.assign({}, option);
  586. const builder = new PageQueryBuilder(this.find({ _id: { $in: ids } }));
  587. builder.addConditionToExcludeRedirect();
  588. builder.addConditionToPagenate(opt.offset, opt.limit);
  589. // count
  590. const totalCount = await builder.query.exec('count');
  591. // find
  592. builder.populateDataToList(User.USER_FIELDS_EXCEPT_CONFIDENTIAL);
  593. const pages = await builder.query.exec('find');
  594. const result = {
  595. pages, totalCount, offset: opt.offset, limit: opt.limit,
  596. };
  597. return result;
  598. };
  599. /**
  600. * find pages by PageQueryBuilder
  601. * @param {PageQueryBuilder} builder
  602. * @param {User} user
  603. * @param {boolean} showAnyoneKnowsLink
  604. * @param {any} option
  605. */
  606. async function findListFromBuilderAndViewer(builder, user, showAnyoneKnowsLink, option) {
  607. validateCrowi();
  608. const User = crowi.model('User');
  609. const opt = Object.assign({ sort: 'updatedAt', desc: -1 }, option);
  610. const sortOpt = {};
  611. sortOpt[opt.sort] = opt.desc;
  612. // exclude trashed pages
  613. if (!opt.includeTrashed) {
  614. builder.addConditionToExcludeTrashed();
  615. }
  616. // exclude redirect pages
  617. if (!opt.includeRedirect) {
  618. builder.addConditionToExcludeRedirect();
  619. }
  620. // add grant conditions
  621. await addConditionToFilteringByViewerForList(builder, user, showAnyoneKnowsLink);
  622. // count
  623. const totalCount = await builder.query.exec('count');
  624. // find
  625. builder.addConditionToPagenate(opt.offset, opt.limit, sortOpt);
  626. builder.populateDataToList(User.USER_FIELDS_EXCEPT_CONFIDENTIAL);
  627. const pages = await builder.query.exec('find');
  628. const result = {
  629. pages, totalCount, offset: opt.offset, limit: opt.limit,
  630. };
  631. return result;
  632. }
  633. /**
  634. * Add condition that filter pages by viewer
  635. * by considering Config
  636. *
  637. * @param {PageQueryBuilder} builder
  638. * @param {User} user
  639. * @param {boolean} showAnyoneKnowsLink
  640. */
  641. async function addConditionToFilteringByViewerForList(builder, user, showAnyoneKnowsLink) {
  642. validateCrowi();
  643. // determine User condition
  644. const hidePagesRestrictedByOwner = crowi.configManager.getConfig('crowi', 'security:list-policy:hideRestrictedByOwner');
  645. const hidePagesRestrictedByGroup = crowi.configManager.getConfig('crowi', 'security:list-policy:hideRestrictedByGroup');
  646. // determine UserGroup condition
  647. let userGroups = null;
  648. if (user != null) {
  649. const UserGroupRelation = crowi.model('UserGroupRelation');
  650. userGroups = await UserGroupRelation.findAllUserGroupIdsRelatedToUser(user);
  651. }
  652. return builder.addConditionToFilteringByViewer(user, userGroups, showAnyoneKnowsLink, !hidePagesRestrictedByOwner, !hidePagesRestrictedByGroup);
  653. }
  654. /**
  655. * Add condition that filter pages by viewer
  656. * by considering Config
  657. *
  658. * @param {PageQueryBuilder} builder
  659. * @param {User} user
  660. * @param {boolean} showAnyoneKnowsLink
  661. */
  662. async function addConditionToFilteringByViewerToEdit(builder, user) {
  663. validateCrowi();
  664. // determine UserGroup condition
  665. let userGroups = null;
  666. if (user != null) {
  667. const UserGroupRelation = crowi.model('UserGroupRelation');
  668. userGroups = await UserGroupRelation.findAllUserGroupIdsRelatedToUser(user);
  669. }
  670. return builder.addConditionToFilteringByViewer(user, userGroups, false, false, false);
  671. }
  672. /**
  673. * export addConditionToFilteringByViewerForList as static method
  674. */
  675. pageSchema.statics.addConditionToFilteringByViewerForList = addConditionToFilteringByViewerForList;
  676. /**
  677. * Throw error for growi-lsx-plugin (v1.x)
  678. */
  679. pageSchema.statics.generateQueryToListByStartWith = function(path, user, option) {
  680. const dummyQuery = this.find();
  681. dummyQuery.exec = async() => {
  682. throw new Error('Plugin version mismatch. Upgrade growi-lsx-plugin to v2.0.0 or above.');
  683. };
  684. return dummyQuery;
  685. };
  686. pageSchema.statics.generateQueryToListWithDescendants = pageSchema.statics.generateQueryToListByStartWith;
  687. /**
  688. * find all templates applicable to the new page
  689. */
  690. pageSchema.statics.findTemplate = async function(path) {
  691. const templatePath = nodePath.posix.dirname(path);
  692. const pathList = generatePathsOnTree(path, []);
  693. const regexpList = pathList.map((path) => {
  694. const pathWithTrailingSlash = pathUtils.addTrailingSlash(path);
  695. return new RegExp(`^${escapeStringRegexp(pathWithTrailingSlash)}_{1,2}template$`);
  696. });
  697. const templatePages = await this.find({ path: { $in: regexpList } })
  698. .populate({ path: 'revision', model: 'Revision' })
  699. .exec();
  700. return fetchTemplate(templatePages, templatePath);
  701. };
  702. const generatePathsOnTree = (path, pathList) => {
  703. pathList.push(path);
  704. if (path === '/') {
  705. return pathList;
  706. }
  707. const newPath = nodePath.posix.dirname(path);
  708. return generatePathsOnTree(newPath, pathList);
  709. };
  710. const assignTemplateByType = (templates, path, type) => {
  711. const targetTemplatePath = urljoin(path, `${type}template`);
  712. return templates.find((template) => {
  713. return (template.path === targetTemplatePath);
  714. });
  715. };
  716. const assignDecendantsTemplate = (decendantsTemplates, path) => {
  717. const decendantsTemplate = assignTemplateByType(decendantsTemplates, path, '__');
  718. if (decendantsTemplate) {
  719. return decendantsTemplate;
  720. }
  721. if (path === '/') {
  722. return;
  723. }
  724. const newPath = nodePath.posix.dirname(path);
  725. return assignDecendantsTemplate(decendantsTemplates, newPath);
  726. };
  727. const fetchTemplate = async(templates, templatePath) => {
  728. let templateBody;
  729. let templateTags;
  730. /**
  731. * get children template
  732. * __tempate: applicable only to immediate decendants
  733. */
  734. const childrenTemplate = assignTemplateByType(templates, templatePath, '_');
  735. /**
  736. * get decendants templates
  737. * _tempate: applicable to all pages under
  738. */
  739. const decendantsTemplate = assignDecendantsTemplate(templates, templatePath);
  740. if (childrenTemplate) {
  741. templateBody = childrenTemplate.revision.body;
  742. templateTags = await childrenTemplate.findRelatedTagsById();
  743. }
  744. else if (decendantsTemplate) {
  745. templateBody = decendantsTemplate.revision.body;
  746. templateTags = await decendantsTemplate.findRelatedTagsById();
  747. }
  748. return { templateBody, templateTags };
  749. };
  750. async function pushRevision(pageData, newRevision, user) {
  751. await newRevision.save();
  752. debug('Successfully saved new revision', newRevision);
  753. pageData.revision = newRevision;
  754. pageData.lastUpdateUser = user;
  755. pageData.updatedAt = Date.now();
  756. return pageData.save();
  757. }
  758. async function validateAppliedScope(user, grant, grantUserGroupId) {
  759. if (grant === GRANT_USER_GROUP && grantUserGroupId == null) {
  760. throw new Error('grant userGroupId is not specified');
  761. }
  762. if (grant === GRANT_USER_GROUP) {
  763. const UserGroupRelation = crowi.model('UserGroupRelation');
  764. const count = await UserGroupRelation.countByGroupIdAndUser(grantUserGroupId, user);
  765. if (count === 0) {
  766. throw new Error('no relations were exist for group and user.');
  767. }
  768. }
  769. }
  770. pageSchema.statics.create = async function(path, body, user, options = {}) {
  771. validateCrowi();
  772. const Page = this;
  773. const Revision = crowi.model('Revision');
  774. const format = options.format || 'markdown';
  775. const redirectTo = options.redirectTo || null;
  776. const grantUserGroupId = options.grantUserGroupId || null;
  777. const socketClientId = options.socketClientId || null;
  778. // sanitize path
  779. path = crowi.xss.process(path); // eslint-disable-line no-param-reassign
  780. let grant = options.grant;
  781. // force public
  782. if (isTopPage(path)) {
  783. grant = GRANT_PUBLIC;
  784. }
  785. const isExist = await this.count({ path });
  786. if (isExist) {
  787. throw new Error('Cannot create new page to existed path');
  788. }
  789. const page = new Page();
  790. page.path = path;
  791. page.creator = user;
  792. page.lastUpdateUser = user;
  793. page.redirectTo = redirectTo;
  794. page.status = STATUS_PUBLISHED;
  795. await validateAppliedScope(user, grant, grantUserGroupId);
  796. page.applyScope(user, grant, grantUserGroupId);
  797. let savedPage = await page.save();
  798. const newRevision = Revision.prepareRevision(savedPage, body, null, user, { format });
  799. const revision = await pushRevision(savedPage, newRevision, user);
  800. savedPage = await this.findByPath(revision.path);
  801. await savedPage.populateDataToShowRevision();
  802. if (socketClientId != null) {
  803. pageEvent.emit('create', savedPage, user, socketClientId);
  804. }
  805. return savedPage;
  806. };
  807. pageSchema.statics.updatePage = async function(pageData, body, previousBody, user, options = {}) {
  808. validateCrowi();
  809. const Revision = crowi.model('Revision');
  810. const grant = options.grant || pageData.grant; // use the previous data if absence
  811. const grantUserGroupId = options.grantUserGroupId || pageData.grantUserGroupId; // use the previous data if absence
  812. const isSyncRevisionToHackmd = options.isSyncRevisionToHackmd;
  813. const socketClientId = options.socketClientId || null;
  814. await validateAppliedScope(user, grant, grantUserGroupId);
  815. pageData.applyScope(user, grant, grantUserGroupId);
  816. // update existing page
  817. let savedPage = await pageData.save();
  818. const newRevision = await Revision.prepareRevision(pageData, body, previousBody, user);
  819. const revision = await pushRevision(savedPage, newRevision, user);
  820. savedPage = await this.findByPath(revision.path);
  821. await savedPage.populateDataToShowRevision();
  822. if (isSyncRevisionToHackmd) {
  823. savedPage = await this.syncRevisionToHackmd(savedPage);
  824. }
  825. if (socketClientId != null) {
  826. pageEvent.emit('update', savedPage, user, socketClientId);
  827. }
  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. };