obsolete-page.js 33 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187
  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/core');
  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, includeEmpty = false) {
  68. this.query = query;
  69. if (!includeEmpty) {
  70. this.query = this.query
  71. .and({
  72. $or: [
  73. { isEmpty: false },
  74. { isEmpty: null }, // for v4 compatibility
  75. ],
  76. });
  77. }
  78. }
  79. addConditionToExcludeTrashed() {
  80. this.query = this.query
  81. .and({
  82. $or: [
  83. { status: null },
  84. { status: STATUS_PUBLISHED },
  85. ],
  86. });
  87. return this;
  88. }
  89. /**
  90. * generate the query to find the pages '{path}/*' and '{path}' self.
  91. * If top page, return without doing anything.
  92. */
  93. addConditionToListWithDescendants(path, option) {
  94. // No request is set for the top page
  95. if (isTopPage(path)) {
  96. return this;
  97. }
  98. const pathNormalized = pathUtils.normalizePath(path);
  99. const pathWithTrailingSlash = pathUtils.addTrailingSlash(path);
  100. const startsPattern = escapeStringRegexp(pathWithTrailingSlash);
  101. this.query = this.query
  102. .and({
  103. $or: [
  104. { path: pathNormalized },
  105. { path: new RegExp(`^${startsPattern}`) },
  106. ],
  107. });
  108. return this;
  109. }
  110. /**
  111. * generate the query to find the pages '{path}/*' (exclude '{path}' self).
  112. * If top page, return without doing anything.
  113. */
  114. addConditionToListOnlyDescendants(path, option) {
  115. // No request is set for the top page
  116. if (isTopPage(path)) {
  117. return this;
  118. }
  119. const pathWithTrailingSlash = pathUtils.addTrailingSlash(path);
  120. const startsPattern = escapeStringRegexp(pathWithTrailingSlash);
  121. this.query = this.query
  122. .and({ path: new RegExp(`^${startsPattern}`) });
  123. return this;
  124. }
  125. addConditionToListOnlyAncestors(path) {
  126. const pathNormalized = pathUtils.normalizePath(path);
  127. const ancestorsPaths = extractToAncestorsPaths(pathNormalized);
  128. this.query = this.query
  129. .and({
  130. path: {
  131. $in: ancestorsPaths,
  132. },
  133. });
  134. return this;
  135. }
  136. /**
  137. * generate the query to find pages that start with `path`
  138. *
  139. * In normal case, returns '{path}/*' and '{path}' self.
  140. * If top page, return without doing anything.
  141. *
  142. * *option*
  143. * Left for backward compatibility
  144. */
  145. addConditionToListByStartWith(path, option) {
  146. // No request is set for the top page
  147. if (isTopPage(path)) {
  148. return this;
  149. }
  150. const startsPattern = escapeStringRegexp(path);
  151. this.query = this.query
  152. .and({ path: new RegExp(`^${startsPattern}`) });
  153. return this;
  154. }
  155. addConditionToFilteringByViewer(user, userGroups, showAnyoneKnowsLink = false, showPagesRestrictedByOwner = false, showPagesRestrictedByGroup = false) {
  156. const grantConditions = [
  157. { grant: null },
  158. { grant: GRANT_PUBLIC },
  159. ];
  160. if (showAnyoneKnowsLink) {
  161. grantConditions.push({ grant: GRANT_RESTRICTED });
  162. }
  163. if (showPagesRestrictedByOwner) {
  164. grantConditions.push(
  165. { grant: GRANT_SPECIFIED },
  166. { grant: GRANT_OWNER },
  167. );
  168. }
  169. else if (user != null) {
  170. grantConditions.push(
  171. { grant: GRANT_SPECIFIED, grantedUsers: user._id },
  172. { grant: GRANT_OWNER, grantedUsers: user._id },
  173. );
  174. }
  175. if (showPagesRestrictedByGroup) {
  176. grantConditions.push(
  177. { grant: GRANT_USER_GROUP },
  178. );
  179. }
  180. else if (userGroups != null && userGroups.length > 0) {
  181. grantConditions.push(
  182. { grant: GRANT_USER_GROUP, grantedGroup: { $in: userGroups } },
  183. );
  184. }
  185. this.query = this.query
  186. .and({
  187. $or: grantConditions,
  188. });
  189. return this;
  190. }
  191. addConditionToPagenate(offset, limit, sortOpt) {
  192. this.query = this.query
  193. .sort(sortOpt).skip(offset).limit(limit); // eslint-disable-line newline-per-chained-call
  194. return this;
  195. }
  196. addConditionAsNonRootPage() {
  197. this.query = this.query.and({ path: { $ne: '/' } });
  198. return this;
  199. }
  200. addConditionAsNotMigrated() {
  201. this.query = this.query
  202. .and({ parent: null });
  203. return this;
  204. }
  205. addConditionAsMigrated() {
  206. this.query = this.query
  207. .and(
  208. {
  209. $or: [
  210. { parent: { $ne: null } },
  211. { path: '/' },
  212. ],
  213. },
  214. );
  215. return this;
  216. }
  217. /*
  218. * Add this condition when get any ancestor pages including the target's parent
  219. */
  220. addConditionToSortPagesByDescPath() {
  221. this.query = this.query.sort('-path');
  222. return this;
  223. }
  224. addConditionToSortPagesByAscPath() {
  225. this.query = this.query.sort('path');
  226. return this;
  227. }
  228. addConditionToMinimizeDataForRendering() {
  229. this.query = this.query.select('_id path isEmpty grant revision');
  230. return this;
  231. }
  232. addConditionToListByPathsArray(paths) {
  233. this.query = this.query
  234. .and({
  235. path: {
  236. $in: paths,
  237. },
  238. });
  239. return this;
  240. }
  241. addConditionToListByPageIdsArray(pageIds) {
  242. this.query = this.query
  243. .and({
  244. _id: {
  245. $in: pageIds,
  246. },
  247. });
  248. return this;
  249. }
  250. populateDataToList(userPublicFields) {
  251. this.query = this.query
  252. .populate({
  253. path: 'lastUpdateUser',
  254. select: userPublicFields,
  255. });
  256. return this;
  257. }
  258. populateDataToShowRevision(userPublicFields) {
  259. this.query = populateDataToShowRevision(this.query, userPublicFields);
  260. return this;
  261. }
  262. addConditionToFilteringByParentId(parentId) {
  263. this.query = this.query.and({ parent: parentId });
  264. return this;
  265. }
  266. }
  267. export const getPageSchema = (crowi) => {
  268. let pageEvent;
  269. // init event
  270. if (crowi != null) {
  271. pageEvent = crowi.event('page');
  272. pageEvent.on('create', pageEvent.onCreate);
  273. pageEvent.on('update', pageEvent.onUpdate);
  274. pageEvent.on('createMany', pageEvent.onCreateMany);
  275. pageEvent.on('addSeenUsers', pageEvent.onAddSeenUsers);
  276. }
  277. function validateCrowi() {
  278. if (crowi == null) {
  279. throw new Error('"crowi" is null. Init User model with "crowi" argument first.');
  280. }
  281. }
  282. pageSchema.methods.isDeleted = function() {
  283. return (this.status === STATUS_DELETED) || isTrashPage(this.path);
  284. };
  285. pageSchema.methods.isPublic = function() {
  286. if (!this.grant || this.grant === GRANT_PUBLIC) {
  287. return true;
  288. }
  289. return false;
  290. };
  291. pageSchema.methods.isTopPage = function() {
  292. return isTopPage(this.path);
  293. };
  294. pageSchema.methods.isTemplate = function() {
  295. return checkTemplatePath(this.path);
  296. };
  297. pageSchema.methods.isLatestRevision = function() {
  298. // populate されていなくて判断できない
  299. if (!this.latestRevision || !this.revision) {
  300. return true;
  301. }
  302. // comparing ObjectId with string
  303. // eslint-disable-next-line eqeqeq
  304. return (this.latestRevision == this.revision._id.toString());
  305. };
  306. pageSchema.methods.findRelatedTagsById = async function() {
  307. const PageTagRelation = mongoose.model('PageTagRelation');
  308. const relations = await PageTagRelation.find({ relatedPage: this._id }).populate('relatedTag');
  309. return relations.map((relation) => { return relation.relatedTag.name });
  310. };
  311. pageSchema.methods.isUpdatable = function(previousRevision) {
  312. const revision = this.latestRevision || this.revision;
  313. // comparing ObjectId with string
  314. // eslint-disable-next-line eqeqeq
  315. if (revision != previousRevision) {
  316. return false;
  317. }
  318. return true;
  319. };
  320. pageSchema.methods.isLiked = function(user) {
  321. if (user == null || user._id == null) {
  322. return false;
  323. }
  324. return this.liker.some((likedUserId) => {
  325. return likedUserId.toString() === user._id.toString();
  326. });
  327. };
  328. pageSchema.methods.like = function(userData) {
  329. const self = this;
  330. return new Promise(((resolve, reject) => {
  331. const added = self.liker.addToSet(userData._id);
  332. if (added.length > 0) {
  333. self.save((err, data) => {
  334. if (err) {
  335. return reject(err);
  336. }
  337. logger.debug('liker updated!', added);
  338. return resolve(data);
  339. });
  340. }
  341. else {
  342. logger.debug('liker not updated');
  343. return reject(new Error('Already liked'));
  344. }
  345. }));
  346. };
  347. pageSchema.methods.unlike = function(userData, callback) {
  348. const self = this;
  349. return new Promise(((resolve, reject) => {
  350. const beforeCount = self.liker.length;
  351. self.liker.pull(userData._id);
  352. if (self.liker.length !== beforeCount) {
  353. self.save((err, data) => {
  354. if (err) {
  355. return reject(err);
  356. }
  357. return resolve(data);
  358. });
  359. }
  360. else {
  361. logger.debug('liker not updated');
  362. return reject(new Error('Already unliked'));
  363. }
  364. }));
  365. };
  366. pageSchema.methods.isSeenUser = function(userData) {
  367. return this.seenUsers.includes(userData._id);
  368. };
  369. pageSchema.methods.seen = async function(userData) {
  370. if (this.isSeenUser(userData)) {
  371. debug('seenUsers not updated');
  372. return this;
  373. }
  374. if (!userData || !userData._id) {
  375. throw new Error('User data is not valid');
  376. }
  377. const added = this.seenUsers.addToSet(userData._id);
  378. const saved = await this.save();
  379. debug('seenUsers updated!', added);
  380. pageEvent.emit('addSeenUsers', saved);
  381. return saved;
  382. };
  383. pageSchema.methods.updateSlackChannels = function(slackChannels) {
  384. this.slackChannels = slackChannels;
  385. return this.save();
  386. };
  387. pageSchema.methods.initLatestRevisionField = async function(revisionId) {
  388. this.latestRevision = this.revision;
  389. if (revisionId != null) {
  390. this.revision = revisionId;
  391. }
  392. };
  393. pageSchema.methods.populateDataToShowRevision = async function() {
  394. validateCrowi();
  395. const User = crowi.model('User');
  396. return populateDataToShowRevision(this, User.USER_FIELDS_EXCEPT_CONFIDENTIAL);
  397. };
  398. pageSchema.methods.populateDataToMakePresentation = async function(revisionId) {
  399. this.latestRevision = this.revision;
  400. if (revisionId != null) {
  401. this.revision = revisionId;
  402. }
  403. return this.populate('revision');
  404. };
  405. pageSchema.methods.applyScope = function(user, grant, grantUserGroupId) {
  406. // reset
  407. this.grantedUsers = [];
  408. this.grantedGroup = null;
  409. this.grant = grant || GRANT_PUBLIC;
  410. if (grant !== GRANT_PUBLIC && grant !== GRANT_USER_GROUP) {
  411. this.grantedUsers.push(user._id);
  412. }
  413. if (grant === GRANT_USER_GROUP) {
  414. this.grantedGroup = grantUserGroupId;
  415. }
  416. };
  417. pageSchema.methods.getContentAge = function() {
  418. return differenceInYears(new Date(), this.updatedAt);
  419. };
  420. pageSchema.statics.updateCommentCount = function(pageId) {
  421. validateCrowi();
  422. const self = this;
  423. const Comment = crowi.model('Comment');
  424. return Comment.countCommentByPageId(pageId)
  425. .then((count) => {
  426. self.update({ _id: pageId }, { commentCount: count }, {}, (err, data) => {
  427. if (err) {
  428. debug('Update commentCount Error', err);
  429. throw err;
  430. }
  431. return data;
  432. });
  433. });
  434. };
  435. pageSchema.statics.getGrantLabels = function() {
  436. const grantLabels = {};
  437. grantLabels[GRANT_PUBLIC] = 'Public'; // 公開
  438. grantLabels[GRANT_RESTRICTED] = 'Anyone with the link'; // リンクを知っている人のみ
  439. // grantLabels[GRANT_SPECIFIED] = 'Specified users only'; // 特定ユーザーのみ
  440. grantLabels[GRANT_USER_GROUP] = 'Only inside the group'; // 特定グループのみ
  441. grantLabels[GRANT_OWNER] = 'Only me'; // 自分のみ
  442. return grantLabels;
  443. };
  444. pageSchema.statics.getUserPagePath = function(user) {
  445. return `/user/${user.username}`;
  446. };
  447. pageSchema.statics.getDeletedPageName = function(path) {
  448. if (path.match('/')) {
  449. // eslint-disable-next-line no-param-reassign
  450. path = path.substr(1);
  451. }
  452. return `/trash/${path}`;
  453. };
  454. pageSchema.statics.getRevertDeletedPageName = function(path) {
  455. return path.replace('/trash', '');
  456. };
  457. pageSchema.statics.isDeletableName = function(path) {
  458. const notDeletable = [
  459. /^\/user\/[^/]+$/, // user page
  460. ];
  461. for (let i = 0; i < notDeletable.length; i++) {
  462. const pattern = notDeletable[i];
  463. if (path.match(pattern)) {
  464. return false;
  465. }
  466. }
  467. return true;
  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, excludeRedirect = true) {
  605. const User = crowi.model('User');
  606. const opt = Object.assign({}, option);
  607. const builder = new PageQueryBuilder(this.find({ _id: { $in: ids } }));
  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. };