page.js 40 KB

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