page.js 35 KB

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