page.js 38 KB

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