page.js 40 KB

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