obsolete-page.js 32 KB

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