page.js 38 KB

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