obsolete-page.js 34 KB

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