page.js 35 KB

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