page.js 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236
  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. page.grantedGroup = grantUserGroupId;
  702. }
  703. }
  704. pageSchema.statics.create = function(path, body, user, options = {}) {
  705. validateCrowi();
  706. const Page = this
  707. , Revision = crowi.model('Revision')
  708. , format = options.format || 'markdown'
  709. , redirectTo = options.redirectTo || null
  710. , grantUserGroupId = options.grantUserGroupId || null
  711. , socketClientId = options.socketClientId || null
  712. ;
  713. let grant = options.grant || GRANT_PUBLIC;
  714. // sanitize path
  715. path = crowi.xss.process(path);
  716. // force public
  717. if (isPortalPath(path)) {
  718. grant = GRANT_PUBLIC;
  719. }
  720. let savedPage = undefined;
  721. return Page.findOne({path: path})
  722. .then(pageData => {
  723. if (pageData) {
  724. throw new Error('Cannot create new page to existed path');
  725. }
  726. const newPage = new Page();
  727. newPage.path = path;
  728. newPage.creator = user;
  729. newPage.lastUpdateUser = user;
  730. newPage.createdAt = Date.now();
  731. newPage.updatedAt = Date.now();
  732. newPage.redirectTo = redirectTo;
  733. newPage.status = STATUS_PUBLISHED;
  734. applyGrant(newPage, user, grant, grantUserGroupId);
  735. return newPage.save();
  736. })
  737. .then((newPage) => {
  738. savedPage = newPage;
  739. })
  740. .then(() => {
  741. const newRevision = Revision.prepareRevision(savedPage, body, null, user, {format: format});
  742. return pushRevision(savedPage, newRevision, user);
  743. })
  744. .then(() => {
  745. if (socketClientId != null) {
  746. pageEvent.emit('create', savedPage, user, socketClientId);
  747. }
  748. return savedPage;
  749. });
  750. };
  751. pageSchema.statics.updatePage = async function(pageData, body, previousBody, user, options = {}) {
  752. validateCrowi();
  753. const Page = this
  754. , Revision = crowi.model('Revision')
  755. , grant = options.grant || null
  756. , grantUserGroupId = options.grantUserGroupId || null
  757. , isSyncRevisionToHackmd = options.isSyncRevisionToHackmd
  758. , socketClientId = options.socketClientId || null
  759. ;
  760. // update existing page
  761. applyGrant(pageData, user, grant, grantUserGroupId);
  762. let savedPage = await pageData.save();
  763. const newRevision = await Revision.prepareRevision(pageData, body, previousBody, user);
  764. const revision = await pushRevision(savedPage, newRevision, user, grant, grantUserGroupId);
  765. savedPage = await Page.findByPath(revision.path).populate('revision').populate('creator');
  766. if (isSyncRevisionToHackmd) {
  767. savedPage = await Page.syncRevisionToHackmd(savedPage);
  768. }
  769. if (socketClientId != null) {
  770. pageEvent.emit('update', savedPage, user, socketClientId);
  771. }
  772. return savedPage;
  773. };
  774. pageSchema.statics.deletePage = async function(pageData, user, options = {}) {
  775. const newPath = this.getDeletedPageName(pageData.path)
  776. , isTrashed = checkIfTrashed(pageData.path)
  777. , socketClientId = options.socketClientId || null
  778. ;
  779. if (this.isDeletableName(pageData.path)) {
  780. if (isTrashed) {
  781. return this.completelyDeletePage(pageData, user, options);
  782. }
  783. pageData.status = STATUS_DELETED;
  784. const updatedPageData = await this.rename(pageData, newPath, user, {createRedirectPage: true});
  785. if (socketClientId != null) {
  786. pageEvent.emit('delete', updatedPageData, user, socketClientId);
  787. }
  788. return updatedPageData;
  789. }
  790. else {
  791. return Promise.reject('Page is not deletable.');
  792. }
  793. };
  794. const checkIfTrashed = (path) => {
  795. return (path.search(/^\/trash/) !== -1);
  796. };
  797. pageSchema.statics.deletePageRecursively = async function(targetPage, user, options = {}) {
  798. const isTrashed = checkIfTrashed(targetPage.path);
  799. if (isTrashed) {
  800. return this.completelyDeletePageRecursively(targetPage, user, options);
  801. }
  802. const findOpts = { includeRedirect: true };
  803. const result = await this.findListWithDescendants(targetPage.path, user, findOpts);
  804. const pages = result.pages;
  805. let updatedPage = null;
  806. await Promise.all(pages.map(page => {
  807. const isParent = (page.path === targetPage.path);
  808. const p = this.deletePage(page, user, options);
  809. if (isParent) {
  810. updatedPage = p;
  811. }
  812. return p;
  813. }));
  814. return updatedPage;
  815. };
  816. pageSchema.statics.revertDeletedPage = async function(page, user, options = {}) {
  817. const newPath = this.getRevertDeletedPageName(page.path);
  818. const originPage = await this.findByPath(newPath);
  819. if (originPage != null) {
  820. // 削除時、元ページの path には必ず redirectTo 付きで、ページが作成される。
  821. // そのため、そいつは削除してOK
  822. // が、redirectTo ではないページが存在している場合それは何かがおかしい。(データ補正が必要)
  823. if (originPage.redirectTo !== page.path) {
  824. throw new Error('The new page of to revert is exists and the redirect path of the page is not the deleted page.');
  825. }
  826. await this.completelyDeletePage(originPage, options);
  827. }
  828. page.status = STATUS_PUBLISHED;
  829. page.lastUpdateUser = user;
  830. debug('Revert deleted the page', page, newPath);
  831. const updatedPage = await this.rename(page, newPath, user, {});
  832. return updatedPage;
  833. };
  834. pageSchema.statics.revertDeletedPageRecursively = async function(targetPage, user, options = {}) {
  835. const findOpts = { includeRedirect: true, includeTrashed: true };
  836. const result = await this.findListWithDescendants(targetPage.path, user, findOpts);
  837. const pages = result.pages;
  838. let updatedPage = null;
  839. await Promise.all(pages.map(page => {
  840. const isParent = (page.path === targetPage.path);
  841. const p = this.revertDeletedPage(page, user, options);
  842. if (isParent) {
  843. updatedPage = p;
  844. }
  845. return p;
  846. }));
  847. return updatedPage;
  848. };
  849. /**
  850. * This is danger.
  851. */
  852. pageSchema.statics.completelyDeletePage = async function(pageData, user, options = {}) {
  853. validateCrowi();
  854. // Delete Bookmarks, Attachments, Revisions, Pages and emit delete
  855. const Bookmark = crowi.model('Bookmark');
  856. const Attachment = crowi.model('Attachment');
  857. const Comment = crowi.model('Comment');
  858. const Revision = crowi.model('Revision');
  859. const PageGroupRelation = crowi.model('PageGroupRelation');
  860. const pageId = pageData._id;
  861. const socketClientId = options.socketClientId || null;
  862. debug('Completely delete', pageData.path);
  863. await Bookmark.removeBookmarksByPageId(pageId);
  864. await Attachment.removeAttachmentsByPageId(pageId);
  865. await Comment.removeCommentsByPageId(pageId);
  866. await Revision.removeRevisionsByPath(pageData.path);
  867. await this.findByIdAndRemove(pageId);
  868. await this.removeRedirectOriginPageByPath(pageData.path);
  869. await PageGroupRelation.removeAllByPage(pageData);
  870. if (socketClientId != null) {
  871. pageEvent.emit('delete', pageData, user, socketClientId); // update as renamed page
  872. }
  873. return pageData;
  874. };
  875. /**
  876. * Delete Bookmarks, Attachments, Revisions, Pages and emit delete
  877. */
  878. pageSchema.statics.completelyDeletePageRecursively = async function(pageData, user, options = {}) {
  879. const path = pageData.path;
  880. const findOpts = { includeRedirect: true, includeTrashed: true };
  881. const result = await this.findListWithDescendants(path, user, findOpts);
  882. const pages = result.pages;
  883. await Promise.all(pages.map(page => {
  884. return this.completelyDeletePage(page, user, options);
  885. }));
  886. return pageData;
  887. };
  888. pageSchema.statics.removeByPath = function(path) {
  889. if (path == null) {
  890. throw new Error('path is required');
  891. }
  892. return this.findOneAndRemove({ path }).exec();
  893. };
  894. /**
  895. * remove the page that is redirecting to specified `pagePath` recursively
  896. * ex: when
  897. * '/page1' redirects to '/page2' and
  898. * '/page2' redirects to '/page3'
  899. * and given '/page3',
  900. * '/page1' and '/page2' will be removed
  901. *
  902. * @param {string} pagePath
  903. */
  904. pageSchema.statics.removeRedirectOriginPageByPath = async function(pagePath) {
  905. const redirectPage = await this.findByRedirectTo(pagePath);
  906. if (redirectPage == null) {
  907. return;
  908. }
  909. // remove
  910. await this.findByIdAndRemove(redirectPage.id);
  911. // remove recursive
  912. await this.removeRedirectOriginPageByPath(redirectPage.path);
  913. };
  914. pageSchema.statics.rename = async function(pageData, newPagePath, user, options) {
  915. validateCrowi();
  916. const Page = this
  917. , Revision = crowi.model('Revision')
  918. , path = pageData.path
  919. , createRedirectPage = options.createRedirectPage || 0
  920. , socketClientId = options.socketClientId || null
  921. ;
  922. // sanitize path
  923. newPagePath = crowi.xss.process(newPagePath);
  924. // update Page
  925. pageData.path = newPagePath;
  926. pageData.lastUpdateUser = user;
  927. pageData.updatedAt = Date.now();
  928. const updatedPageData = await pageData.save();
  929. // update Rivisions
  930. await Revision.updateRevisionListByPath(path, {path: newPagePath}, {});
  931. if (createRedirectPage) {
  932. const body = 'redirect ' + newPagePath;
  933. await Page.create(path, body, user, {redirectTo: newPagePath});
  934. }
  935. pageEvent.emit('delete', pageData, user, socketClientId);
  936. pageEvent.emit('create', updatedPageData, user, socketClientId);
  937. return updatedPageData;
  938. };
  939. pageSchema.statics.renameRecursively = async function(pageData, newPagePathPrefix, user, options) {
  940. validateCrowi();
  941. const path = pageData.path;
  942. const pathRegExp = new RegExp('^' + escapeStringRegexp(path), 'i');
  943. // sanitize path
  944. newPagePathPrefix = crowi.xss.process(newPagePathPrefix);
  945. const result = await this.findListWithDescendants(path, user, options);
  946. await Promise.all(result.pages.map(page => {
  947. const newPagePath = page.path.replace(pathRegExp, newPagePathPrefix);
  948. return this.rename(page, newPagePath, user, options);
  949. }));
  950. pageData.path = newPagePathPrefix;
  951. return pageData;
  952. };
  953. /**
  954. * associate GROWI page and HackMD page
  955. * @param {Page} pageData
  956. * @param {string} pageIdOnHackmd
  957. */
  958. pageSchema.statics.registerHackmdPage = function(pageData, pageIdOnHackmd) {
  959. if (pageData.pageIdOnHackmd != null) {
  960. throw new Error(`'pageIdOnHackmd' of the page '${pageData.path}' is not empty`);
  961. }
  962. pageData.pageIdOnHackmd = pageIdOnHackmd;
  963. return this.syncRevisionToHackmd(pageData);
  964. };
  965. /**
  966. * update revisionHackmdSynced
  967. * @param {Page} pageData
  968. * @param {bool} isSave whether save or not
  969. */
  970. pageSchema.statics.syncRevisionToHackmd = function(pageData, isSave = true) {
  971. pageData.revisionHackmdSynced = pageData.revision;
  972. pageData.hasDraftOnHackmd = false;
  973. let returnData = pageData;
  974. if (isSave) {
  975. returnData = pageData.save();
  976. }
  977. return returnData;
  978. };
  979. /**
  980. * update hasDraftOnHackmd
  981. * !! This will be invoked many time from many people !!
  982. *
  983. * @param {Page} pageData
  984. * @param {Boolean} newValue
  985. */
  986. pageSchema.statics.updateHasDraftOnHackmd = async function(pageData, newValue) {
  987. if (pageData.hasDraftOnHackmd === newValue) {
  988. // do nothing when hasDraftOnHackmd equals to newValue
  989. return;
  990. }
  991. pageData.hasDraftOnHackmd = newValue;
  992. return pageData.save();
  993. };
  994. pageSchema.statics.getHistories = function() {
  995. // TODO
  996. return;
  997. };
  998. /**
  999. * return path that added slash to the end for specified path
  1000. */
  1001. pageSchema.statics.addSlashOfEnd = function(path) {
  1002. return addSlashOfEnd(path);
  1003. };
  1004. pageSchema.statics.allPageCount = function() {
  1005. return this.count({ redirectTo: null });
  1006. };
  1007. pageSchema.statics.GRANT_PUBLIC = GRANT_PUBLIC;
  1008. pageSchema.statics.GRANT_RESTRICTED = GRANT_RESTRICTED;
  1009. pageSchema.statics.GRANT_SPECIFIED = GRANT_SPECIFIED;
  1010. pageSchema.statics.GRANT_OWNER = GRANT_OWNER;
  1011. pageSchema.statics.GRANT_USER_GROUP = GRANT_USER_GROUP;
  1012. pageSchema.statics.PAGE_GRANT_ERROR = PAGE_GRANT_ERROR;
  1013. pageSchema.statics.PageQueryBuilder = PageQueryBuilder;
  1014. return mongoose.model('Page', pageSchema);
  1015. };