obsolete-page.js 33 KB

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