obsolete-page.js 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179
  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. pageEvent.on('addSeenUsers', pageEvent.onAddSeenUsers);
  245. }
  246. function validateCrowi() {
  247. if (crowi == null) {
  248. throw new Error('"crowi" is null. Init User model with "crowi" argument first.');
  249. }
  250. }
  251. pageSchema.methods.isDeleted = function() {
  252. return (this.status === STATUS_DELETED) || isTrashPage(this.path);
  253. };
  254. pageSchema.methods.isPublic = function() {
  255. if (!this.grant || this.grant === GRANT_PUBLIC) {
  256. return true;
  257. }
  258. return false;
  259. };
  260. pageSchema.methods.isTopPage = function() {
  261. return isTopPage(this.path);
  262. };
  263. pageSchema.methods.isTemplate = function() {
  264. return checkTemplatePath(this.path);
  265. };
  266. pageSchema.methods.isLatestRevision = function() {
  267. // populate されていなくて判断できない
  268. if (!this.latestRevision || !this.revision) {
  269. return true;
  270. }
  271. // comparing ObjectId with string
  272. // eslint-disable-next-line eqeqeq
  273. return (this.latestRevision == this.revision._id.toString());
  274. };
  275. pageSchema.methods.findRelatedTagsById = async function() {
  276. const PageTagRelation = mongoose.model('PageTagRelation');
  277. const relations = await PageTagRelation.find({ relatedPage: this._id }).populate('relatedTag');
  278. return relations.map((relation) => { return relation.relatedTag.name });
  279. };
  280. pageSchema.methods.isUpdatable = function(previousRevision) {
  281. const revision = this.latestRevision || this.revision;
  282. // comparing ObjectId with string
  283. // eslint-disable-next-line eqeqeq
  284. if (revision != previousRevision) {
  285. return false;
  286. }
  287. return true;
  288. };
  289. pageSchema.methods.isLiked = function(user) {
  290. if (user == null || user._id == null) {
  291. return false;
  292. }
  293. return this.liker.some((likedUserId) => {
  294. return likedUserId.toString() === user._id.toString();
  295. });
  296. };
  297. pageSchema.methods.like = function(userData) {
  298. const self = this;
  299. return new Promise(((resolve, reject) => {
  300. const added = self.liker.addToSet(userData._id);
  301. if (added.length > 0) {
  302. self.save((err, data) => {
  303. if (err) {
  304. return reject(err);
  305. }
  306. logger.debug('liker updated!', added);
  307. return resolve(data);
  308. });
  309. }
  310. else {
  311. logger.debug('liker not updated');
  312. return reject(self);
  313. }
  314. }));
  315. };
  316. pageSchema.methods.unlike = function(userData, callback) {
  317. const self = this;
  318. return new Promise(((resolve, reject) => {
  319. const beforeCount = self.liker.length;
  320. self.liker.pull(userData._id);
  321. if (self.liker.length !== beforeCount) {
  322. self.save((err, data) => {
  323. if (err) {
  324. return reject(err);
  325. }
  326. return resolve(data);
  327. });
  328. }
  329. else {
  330. logger.debug('liker not updated');
  331. return reject(self);
  332. }
  333. }));
  334. };
  335. pageSchema.methods.isSeenUser = function(userData) {
  336. return this.seenUsers.includes(userData._id);
  337. };
  338. pageSchema.methods.seen = async function(userData) {
  339. if (this.isSeenUser(userData)) {
  340. debug('seenUsers not updated');
  341. return this;
  342. }
  343. if (!userData || !userData._id) {
  344. throw new Error('User data is not valid');
  345. }
  346. const added = this.seenUsers.addToSet(userData._id);
  347. const saved = await this.save();
  348. debug('seenUsers updated!', added);
  349. pageEvent.emit('addSeenUsers', saved);
  350. return saved;
  351. };
  352. pageSchema.methods.updateSlackChannels = function(slackChannels) {
  353. this.slackChannels = slackChannels;
  354. return this.save();
  355. };
  356. pageSchema.methods.initLatestRevisionField = async function(revisionId) {
  357. this.latestRevision = this.revision;
  358. if (revisionId != null) {
  359. this.revision = revisionId;
  360. }
  361. };
  362. pageSchema.methods.populateDataToShowRevision = async function() {
  363. validateCrowi();
  364. const User = crowi.model('User');
  365. return populateDataToShowRevision(this, User.USER_FIELDS_EXCEPT_CONFIDENTIAL);
  366. };
  367. pageSchema.methods.populateDataToMakePresentation = async function(revisionId) {
  368. this.latestRevision = this.revision;
  369. if (revisionId != null) {
  370. this.revision = revisionId;
  371. }
  372. return this.populate('revision');
  373. };
  374. pageSchema.methods.applyScope = function(user, grant, grantUserGroupId) {
  375. // reset
  376. this.grantedUsers = [];
  377. this.grantedGroup = null;
  378. this.grant = grant || GRANT_PUBLIC;
  379. if (grant !== GRANT_PUBLIC && grant !== GRANT_USER_GROUP) {
  380. this.grantedUsers.push(user._id);
  381. }
  382. if (grant === GRANT_USER_GROUP) {
  383. this.grantedGroup = grantUserGroupId;
  384. }
  385. };
  386. pageSchema.methods.getContentAge = function() {
  387. return differenceInYears(new Date(), this.updatedAt);
  388. };
  389. pageSchema.statics.updateCommentCount = function(pageId) {
  390. validateCrowi();
  391. const self = this;
  392. const Comment = crowi.model('Comment');
  393. return Comment.countCommentByPageId(pageId)
  394. .then((count) => {
  395. self.update({ _id: pageId }, { commentCount: count }, {}, (err, data) => {
  396. if (err) {
  397. debug('Update commentCount Error', err);
  398. throw err;
  399. }
  400. return data;
  401. });
  402. });
  403. };
  404. pageSchema.statics.getGrantLabels = function() {
  405. const grantLabels = {};
  406. grantLabels[GRANT_PUBLIC] = 'Public'; // 公開
  407. grantLabels[GRANT_RESTRICTED] = 'Anyone with the link'; // リンクを知っている人のみ
  408. // grantLabels[GRANT_SPECIFIED] = 'Specified users only'; // 特定ユーザーのみ
  409. grantLabels[GRANT_USER_GROUP] = 'Only inside the group'; // 特定グループのみ
  410. grantLabels[GRANT_OWNER] = 'Only me'; // 自分のみ
  411. return grantLabels;
  412. };
  413. pageSchema.statics.getUserPagePath = function(user) {
  414. return `/user/${user.username}`;
  415. };
  416. pageSchema.statics.getDeletedPageName = function(path) {
  417. if (path.match('/')) {
  418. // eslint-disable-next-line no-param-reassign
  419. path = path.substr(1);
  420. }
  421. return `/trash/${path}`;
  422. };
  423. pageSchema.statics.getRevertDeletedPageName = function(path) {
  424. return path.replace('/trash', '');
  425. };
  426. pageSchema.statics.isDeletableName = function(path) {
  427. const notDeletable = [
  428. /^\/user\/[^/]+$/, // user page
  429. ];
  430. for (let i = 0; i < notDeletable.length; i++) {
  431. const pattern = notDeletable[i];
  432. if (path.match(pattern)) {
  433. return false;
  434. }
  435. }
  436. return true;
  437. };
  438. pageSchema.statics.fixToCreatableName = function(path) {
  439. return path
  440. .replace(/\/\//g, '/');
  441. };
  442. pageSchema.statics.updateRevision = function(pageId, revisionId, cb) {
  443. this.update({ _id: pageId }, { revision: revisionId }, {}, (err, data) => {
  444. cb(err, data);
  445. });
  446. };
  447. /**
  448. * return whether the user is accessible to the page
  449. * @param {string} id ObjectId
  450. * @param {User} user
  451. */
  452. pageSchema.statics.isAccessiblePageByViewer = async function(id, user) {
  453. const baseQuery = this.count({ _id: id });
  454. let userGroups = [];
  455. if (user != null) {
  456. validateCrowi();
  457. const UserGroupRelation = crowi.model('UserGroupRelation');
  458. userGroups = await UserGroupRelation.findAllUserGroupIdsRelatedToUser(user);
  459. }
  460. const queryBuilder = new PageQueryBuilder(baseQuery);
  461. queryBuilder.addConditionToFilteringByViewer(user, userGroups, true);
  462. const count = await queryBuilder.query.exec();
  463. return count > 0;
  464. };
  465. /**
  466. * @param {string} id ObjectId
  467. * @param {User} user User instance
  468. * @param {UserGroup[]} userGroups List of UserGroup instances
  469. */
  470. pageSchema.statics.findByIdAndViewer = async function(id, user, userGroups) {
  471. const baseQuery = this.findOne({ _id: id });
  472. let relatedUserGroups = userGroups;
  473. if (user != null && relatedUserGroups == null) {
  474. validateCrowi();
  475. const UserGroupRelation = crowi.model('UserGroupRelation');
  476. relatedUserGroups = await UserGroupRelation.findAllUserGroupIdsRelatedToUser(user);
  477. }
  478. const queryBuilder = new PageQueryBuilder(baseQuery);
  479. queryBuilder.addConditionToFilteringByViewer(user, relatedUserGroups, true);
  480. return await queryBuilder.query.exec();
  481. };
  482. // find page by path
  483. pageSchema.statics.findByPath = function(path) {
  484. if (path == null) {
  485. return null;
  486. }
  487. return this.findOne({ path });
  488. };
  489. /**
  490. * @param {string} path Page path
  491. * @param {User} user User instance
  492. * @param {UserGroup[]} userGroups List of UserGroup instances
  493. */
  494. pageSchema.statics.findAncestorByPathAndViewer = async function(path, user, userGroups) {
  495. if (path == null) {
  496. throw new Error('path is required.');
  497. }
  498. if (path === '/') {
  499. return null;
  500. }
  501. const ancestorsPaths = extractToAncestorsPaths(path);
  502. // pick the longest one
  503. const baseQuery = this.findOne({ path: { $in: ancestorsPaths } }).sort({ path: -1 });
  504. let relatedUserGroups = userGroups;
  505. if (user != null && relatedUserGroups == null) {
  506. validateCrowi();
  507. const UserGroupRelation = crowi.model('UserGroupRelation');
  508. relatedUserGroups = await UserGroupRelation.findAllUserGroupIdsRelatedToUser(user);
  509. }
  510. const queryBuilder = new PageQueryBuilder(baseQuery);
  511. queryBuilder.addConditionToFilteringByViewer(user, relatedUserGroups);
  512. return await queryBuilder.query.exec();
  513. };
  514. pageSchema.statics.findByRedirectTo = function(path) {
  515. return this.findOne({ redirectTo: path });
  516. };
  517. /**
  518. * find pages that is match with `path` and its descendants
  519. */
  520. pageSchema.statics.findListWithDescendants = async function(path, user, option = {}) {
  521. const builder = new PageQueryBuilder(this.find());
  522. builder.addConditionToListWithDescendants(path, option);
  523. return await findListFromBuilderAndViewer(builder, user, false, option);
  524. };
  525. /**
  526. * find pages that is match with `path` and its descendants whitch user is able to manage
  527. */
  528. pageSchema.statics.findManageableListWithDescendants = async function(page, user, option = {}) {
  529. if (user == null) {
  530. return null;
  531. }
  532. const builder = new PageQueryBuilder(this.find());
  533. builder.addConditionToListWithDescendants(page.path, option);
  534. builder.addConditionToExcludeRedirect();
  535. // add grant conditions
  536. await addConditionToFilteringByViewerToEdit(builder, user);
  537. const { pages } = await findListFromBuilderAndViewer(builder, user, false, option);
  538. // add page if 'grant' is GRANT_RESTRICTED
  539. // because addConditionToListWithDescendants excludes GRANT_RESTRICTED pages
  540. if (page.grant === GRANT_RESTRICTED) {
  541. pages.push(page);
  542. }
  543. return pages;
  544. };
  545. /**
  546. * find pages that start with `path`
  547. */
  548. pageSchema.statics.findListByStartWith = async function(path, user, option) {
  549. const builder = new PageQueryBuilder(this.find());
  550. builder.addConditionToListByStartWith(path, option);
  551. return await findListFromBuilderAndViewer(builder, user, false, option);
  552. };
  553. /**
  554. * find pages that is created by targetUser
  555. *
  556. * @param {User} targetUser
  557. * @param {User} currentUser
  558. * @param {any} option
  559. */
  560. pageSchema.statics.findListByCreator = async function(targetUser, currentUser, option) {
  561. const opt = Object.assign({ sort: 'createdAt', desc: -1 }, option);
  562. const builder = new PageQueryBuilder(this.find({ creator: targetUser._id }));
  563. let showAnyoneKnowsLink = null;
  564. if (targetUser != null && currentUser != null) {
  565. showAnyoneKnowsLink = targetUser._id.equals(currentUser._id);
  566. }
  567. return await findListFromBuilderAndViewer(builder, currentUser, showAnyoneKnowsLink, opt);
  568. };
  569. pageSchema.statics.findListByPageIds = async function(ids, option, excludeRedirect = true) {
  570. const User = crowi.model('User');
  571. const opt = Object.assign({}, option);
  572. const builder = new PageQueryBuilder(this.find({ _id: { $in: ids } }));
  573. if (excludeRedirect) {
  574. builder.addConditionToExcludeRedirect();
  575. }
  576. builder.addConditionToPagenate(opt.offset, opt.limit);
  577. // count
  578. const totalCount = await builder.query.exec('count');
  579. // find
  580. builder.populateDataToList(User.USER_FIELDS_EXCEPT_CONFIDENTIAL);
  581. const pages = await builder.query.clone().exec('find');
  582. const result = {
  583. pages, totalCount, offset: opt.offset, limit: opt.limit,
  584. };
  585. return result;
  586. };
  587. /**
  588. * find pages by PageQueryBuilder
  589. * @param {PageQueryBuilder} builder
  590. * @param {User} user
  591. * @param {boolean} showAnyoneKnowsLink
  592. * @param {any} option
  593. */
  594. async function findListFromBuilderAndViewer(builder, user, showAnyoneKnowsLink, option) {
  595. validateCrowi();
  596. const User = crowi.model('User');
  597. const opt = Object.assign({ sort: 'updatedAt', desc: -1 }, option);
  598. const sortOpt = {};
  599. sortOpt[opt.sort] = opt.desc;
  600. // exclude trashed pages
  601. if (!opt.includeTrashed) {
  602. builder.addConditionToExcludeTrashed();
  603. }
  604. // exclude redirect pages
  605. if (!opt.includeRedirect) {
  606. builder.addConditionToExcludeRedirect();
  607. }
  608. // add grant conditions
  609. await addConditionToFilteringByViewerForList(builder, user, showAnyoneKnowsLink);
  610. // count
  611. const totalCount = await builder.query.exec('count');
  612. // find
  613. builder.addConditionToPagenate(opt.offset, opt.limit, sortOpt);
  614. builder.populateDataToList(User.USER_FIELDS_EXCEPT_CONFIDENTIAL);
  615. const pages = await builder.query.lean().clone().exec('find');
  616. const result = {
  617. pages, totalCount, offset: opt.offset, limit: opt.limit,
  618. };
  619. return result;
  620. }
  621. /**
  622. * Add condition that filter pages by viewer
  623. * by considering Config
  624. *
  625. * @param {PageQueryBuilder} builder
  626. * @param {User} user
  627. * @param {boolean} showAnyoneKnowsLink
  628. */
  629. async function addConditionToFilteringByViewerForList(builder, user, showAnyoneKnowsLink) {
  630. validateCrowi();
  631. // determine User condition
  632. const hidePagesRestrictedByOwner = crowi.configManager.getConfig('crowi', 'security:list-policy:hideRestrictedByOwner');
  633. const hidePagesRestrictedByGroup = crowi.configManager.getConfig('crowi', 'security:list-policy:hideRestrictedByGroup');
  634. // determine UserGroup condition
  635. let userGroups = null;
  636. if (user != null) {
  637. const UserGroupRelation = crowi.model('UserGroupRelation');
  638. userGroups = await UserGroupRelation.findAllUserGroupIdsRelatedToUser(user);
  639. }
  640. return builder.addConditionToFilteringByViewer(user, userGroups, showAnyoneKnowsLink, !hidePagesRestrictedByOwner, !hidePagesRestrictedByGroup);
  641. }
  642. /**
  643. * Add condition that filter pages by viewer
  644. * by considering Config
  645. *
  646. * @param {PageQueryBuilder} builder
  647. * @param {User} user
  648. * @param {boolean} showAnyoneKnowsLink
  649. */
  650. async function addConditionToFilteringByViewerToEdit(builder, user) {
  651. validateCrowi();
  652. // determine UserGroup condition
  653. let userGroups = null;
  654. if (user != null) {
  655. const UserGroupRelation = crowi.model('UserGroupRelation');
  656. userGroups = await UserGroupRelation.findAllUserGroupIdsRelatedToUser(user);
  657. }
  658. return builder.addConditionToFilteringByViewer(user, userGroups, false, false, false);
  659. }
  660. /**
  661. * export addConditionToFilteringByViewerForList as static method
  662. */
  663. pageSchema.statics.addConditionToFilteringByViewerForList = addConditionToFilteringByViewerForList;
  664. /**
  665. * export addConditionToFilteringByViewerToEdit as static method
  666. */
  667. pageSchema.statics.addConditionToFilteringByViewerToEdit = addConditionToFilteringByViewerToEdit;
  668. /**
  669. * Throw error for growi-lsx-plugin (v1.x)
  670. */
  671. pageSchema.statics.generateQueryToListByStartWith = function(path, user, option) {
  672. const dummyQuery = this.find();
  673. dummyQuery.exec = async() => {
  674. throw new Error('Plugin version mismatch. Upgrade growi-lsx-plugin to v2.0.0 or above.');
  675. };
  676. return dummyQuery;
  677. };
  678. pageSchema.statics.generateQueryToListWithDescendants = pageSchema.statics.generateQueryToListByStartWith;
  679. /**
  680. * find all templates applicable to the new page
  681. */
  682. pageSchema.statics.findTemplate = async function(path) {
  683. const templatePath = nodePath.posix.dirname(path);
  684. const pathList = generatePathsOnTree(path, []);
  685. const regexpList = pathList.map((path) => {
  686. const pathWithTrailingSlash = pathUtils.addTrailingSlash(path);
  687. return new RegExp(`^${escapeStringRegexp(pathWithTrailingSlash)}_{1,2}template$`);
  688. });
  689. const templatePages = await this.find({ path: { $in: regexpList } })
  690. .populate({ path: 'revision', model: 'Revision' })
  691. .exec();
  692. return fetchTemplate(templatePages, templatePath);
  693. };
  694. const generatePathsOnTree = (path, pathList) => {
  695. pathList.push(path);
  696. if (path === '/') {
  697. return pathList;
  698. }
  699. const newPath = nodePath.posix.dirname(path);
  700. return generatePathsOnTree(newPath, pathList);
  701. };
  702. const assignTemplateByType = (templates, path, type) => {
  703. const targetTemplatePath = urljoin(path, `${type}template`);
  704. return templates.find((template) => {
  705. return (template.path === targetTemplatePath);
  706. });
  707. };
  708. const assignDecendantsTemplate = (decendantsTemplates, path) => {
  709. const decendantsTemplate = assignTemplateByType(decendantsTemplates, path, '__');
  710. if (decendantsTemplate) {
  711. return decendantsTemplate;
  712. }
  713. if (path === '/') {
  714. return;
  715. }
  716. const newPath = nodePath.posix.dirname(path);
  717. return assignDecendantsTemplate(decendantsTemplates, newPath);
  718. };
  719. const fetchTemplate = async(templates, templatePath) => {
  720. let templateBody;
  721. let templateTags;
  722. /**
  723. * get children template
  724. * __tempate: applicable only to immediate decendants
  725. */
  726. const childrenTemplate = assignTemplateByType(templates, templatePath, '_');
  727. /**
  728. * get decendants templates
  729. * _tempate: applicable to all pages under
  730. */
  731. const decendantsTemplate = assignDecendantsTemplate(templates, templatePath);
  732. if (childrenTemplate) {
  733. templateBody = childrenTemplate.revision.body;
  734. templateTags = await childrenTemplate.findRelatedTagsById();
  735. }
  736. else if (decendantsTemplate) {
  737. templateBody = decendantsTemplate.revision.body;
  738. templateTags = await decendantsTemplate.findRelatedTagsById();
  739. }
  740. return { templateBody, templateTags };
  741. };
  742. async function pushRevision(pageData, newRevision, user) {
  743. await newRevision.save();
  744. debug('Successfully saved new revision', newRevision);
  745. pageData.revision = newRevision;
  746. pageData.lastUpdateUser = user;
  747. pageData.updatedAt = Date.now();
  748. return pageData.save();
  749. }
  750. async function validateAppliedScope(user, grant, grantUserGroupId) {
  751. if (grant === GRANT_USER_GROUP && grantUserGroupId == null) {
  752. throw new Error('grant userGroupId is not specified');
  753. }
  754. if (grant === GRANT_USER_GROUP) {
  755. const UserGroupRelation = crowi.model('UserGroupRelation');
  756. const count = await UserGroupRelation.countByGroupIdAndUser(grantUserGroupId, user);
  757. if (count === 0) {
  758. throw new Error('no relations were exist for group and user.');
  759. }
  760. }
  761. }
  762. pageSchema.statics.create = async function(path, body, user, options = {}) {
  763. validateCrowi();
  764. const Page = this;
  765. const Revision = crowi.model('Revision');
  766. const {
  767. format = 'markdown', redirectTo, grantUserGroupId, parentId,
  768. } = options;
  769. // sanitize path
  770. path = crowi.xss.process(path); // eslint-disable-line no-param-reassign
  771. let grant = options.grant;
  772. // force public
  773. if (isTopPage(path)) {
  774. grant = GRANT_PUBLIC;
  775. }
  776. const isExist = await this.count({ path, isEmpty: false }); // not validate empty page
  777. if (isExist) {
  778. throw new Error('Cannot create new page to existed path');
  779. }
  780. /*
  781. * update empty page if exists, if not, create a new page
  782. */
  783. let page;
  784. const emptyPage = await Page.findOne({ path, isEmpty: true });
  785. if (emptyPage != null) {
  786. page = emptyPage;
  787. page.isEmpty = false;
  788. }
  789. else {
  790. page = new Page();
  791. }
  792. const isV5Compatible = crowi.configManager.getConfig('crowi', 'app:isV5Compatible');
  793. let parent = parentId;
  794. if (isV5Compatible && parent == null && !isTopPage(path)) {
  795. parent = await Page.getParentIdAndFillAncestors(path);
  796. }
  797. page.path = path;
  798. page.creator = user;
  799. page.lastUpdateUser = user;
  800. page.redirectTo = redirectTo;
  801. page.status = STATUS_PUBLISHED;
  802. page.parent = parent;
  803. await validateAppliedScope(user, grant, grantUserGroupId);
  804. page.applyScope(user, grant, grantUserGroupId);
  805. let savedPage = await page.save();
  806. const newRevision = Revision.prepareRevision(savedPage, body, null, user, { format });
  807. const revision = await pushRevision(savedPage, newRevision, user);
  808. savedPage = await this.findByPath(revision.path);
  809. await savedPage.populateDataToShowRevision();
  810. pageEvent.emit('create', savedPage, user);
  811. return savedPage;
  812. };
  813. pageSchema.statics.updatePage = async function(pageData, body, previousBody, user, options = {}) {
  814. validateCrowi();
  815. const Revision = crowi.model('Revision');
  816. const grant = options.grant || pageData.grant; // use the previous data if absence
  817. const grantUserGroupId = options.grantUserGroupId || pageData.grantUserGroupId; // use the previous data if absence
  818. const isSyncRevisionToHackmd = options.isSyncRevisionToHackmd;
  819. await validateAppliedScope(user, grant, grantUserGroupId);
  820. pageData.applyScope(user, grant, grantUserGroupId);
  821. // update existing page
  822. let savedPage = await pageData.save();
  823. const newRevision = await Revision.prepareRevision(pageData, body, previousBody, user);
  824. const revision = await pushRevision(savedPage, newRevision, user);
  825. savedPage = await this.findByPath(revision.path);
  826. await savedPage.populateDataToShowRevision();
  827. if (isSyncRevisionToHackmd) {
  828. savedPage = await this.syncRevisionToHackmd(savedPage);
  829. }
  830. pageEvent.emit('update', savedPage, user);
  831. return savedPage;
  832. };
  833. pageSchema.statics.applyScopesToDescendantsAsyncronously = async function(parentPage, user) {
  834. const builder = new PageQueryBuilder(this.find());
  835. builder.addConditionToListWithDescendants(parentPage.path);
  836. builder.addConditionToExcludeRedirect();
  837. // add grant conditions
  838. await addConditionToFilteringByViewerToEdit(builder, user);
  839. // get all pages that the specified user can update
  840. const pages = await builder.query.exec();
  841. for (const page of pages) {
  842. // skip parentPage
  843. if (page.id === parentPage.id) {
  844. continue;
  845. }
  846. page.applyScope(user, parentPage.grant, parentPage.grantedGroup);
  847. page.save();
  848. }
  849. };
  850. pageSchema.statics.removeByPath = function(path) {
  851. if (path == null) {
  852. throw new Error('path is required');
  853. }
  854. return this.findOneAndRemove({ path }).exec();
  855. };
  856. /**
  857. * remove the page that is redirecting to specified `pagePath` recursively
  858. * ex: when
  859. * '/page1' redirects to '/page2' and
  860. * '/page2' redirects to '/page3'
  861. * and given '/page3',
  862. * '/page1' and '/page2' will be removed
  863. *
  864. * @param {string} pagePath
  865. */
  866. pageSchema.statics.removeRedirectOriginPageByPath = async function(pagePath) {
  867. const redirectPage = await this.findByRedirectTo(pagePath);
  868. if (redirectPage == null) {
  869. return;
  870. }
  871. // remove
  872. await this.findByIdAndRemove(redirectPage.id);
  873. // remove recursive
  874. await this.removeRedirectOriginPageByPath(redirectPage.path);
  875. };
  876. pageSchema.statics.findListByPathsArray = async function(paths) {
  877. const queryBuilder = new PageQueryBuilder(this.find());
  878. queryBuilder.addConditionToListByPathsArray(paths);
  879. return await queryBuilder.query.exec();
  880. };
  881. pageSchema.statics.publicizePage = async function(page) {
  882. page.grantedGroup = null;
  883. page.grant = GRANT_PUBLIC;
  884. await page.save();
  885. };
  886. pageSchema.statics.transferPageToGroup = async function(page, transferToUserGroupId) {
  887. const UserGroup = mongoose.model('UserGroup');
  888. // check page existence
  889. const isExist = await UserGroup.count({ _id: transferToUserGroupId }) > 0;
  890. if (isExist) {
  891. page.grantedGroup = transferToUserGroupId;
  892. await page.save();
  893. }
  894. else {
  895. throw new Error('Cannot find the group to which private pages belong to. _id: ', transferToUserGroupId);
  896. }
  897. };
  898. /**
  899. * associate GROWI page and HackMD page
  900. * @param {Page} pageData
  901. * @param {string} pageIdOnHackmd
  902. */
  903. pageSchema.statics.registerHackmdPage = function(pageData, pageIdOnHackmd) {
  904. pageData.pageIdOnHackmd = pageIdOnHackmd;
  905. return this.syncRevisionToHackmd(pageData);
  906. };
  907. /**
  908. * update revisionHackmdSynced
  909. * @param {Page} pageData
  910. * @param {bool} isSave whether save or not
  911. */
  912. pageSchema.statics.syncRevisionToHackmd = function(pageData, isSave = true) {
  913. pageData.revisionHackmdSynced = pageData.revision;
  914. pageData.hasDraftOnHackmd = false;
  915. let returnData = pageData;
  916. if (isSave) {
  917. returnData = pageData.save();
  918. }
  919. return returnData;
  920. };
  921. /**
  922. * update hasDraftOnHackmd
  923. * !! This will be invoked many time from many people !!
  924. *
  925. * @param {Page} pageData
  926. * @param {Boolean} newValue
  927. */
  928. pageSchema.statics.updateHasDraftOnHackmd = async function(pageData, newValue) {
  929. if (pageData.hasDraftOnHackmd === newValue) {
  930. // do nothing when hasDraftOnHackmd equals to newValue
  931. return;
  932. }
  933. pageData.hasDraftOnHackmd = newValue;
  934. return pageData.save();
  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. };