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(newTags) {
  258. const page = this;
  259. const PageTagRelation = mongoose.model('PageTagRelation');
  260. const Tag = mongoose.model('Tag');
  261. // get tags relate this page
  262. const relatedTags = await PageTagRelation.find({ relatedPage: page._id }).populate('relatedTag').select('-_id relatedTag');
  263. // unlink relations
  264. const unlinkTagRelations = relatedTags.filter((tag) => { return !newTags.includes(tag.relatedTag.name) });
  265. await PageTagRelation.deleteMany({
  266. relatedPage: page._id,
  267. relatedTag: { $in: unlinkTagRelations.map((relation) => { return relation.relatedTag._id }) },
  268. });
  269. // create tag and relations
  270. newTags.forEach(async(tag) => {
  271. const setTag = await Tag.findOrCreate(tag);
  272. PageTagRelation.createIfNotExist(page._id, setTag._id);
  273. });
  274. return newTags;
  275. };
  276. pageSchema.methods.isPortal = function() {
  277. return isPortalPath(this.path);
  278. };
  279. pageSchema.methods.isTemplate = function() {
  280. return templateChecker(this.path);
  281. };
  282. pageSchema.methods.isLatestRevision = function() {
  283. // populate されていなくて判断できない
  284. if (!this.latestRevision || !this.revision) {
  285. return true;
  286. }
  287. // comparing ObjectId with string
  288. // eslint-disable-next-line eqeqeq
  289. return (this.latestRevision == this.revision._id.toString());
  290. };
  291. pageSchema.methods.isUpdatable = function(previousRevision) {
  292. const revision = this.latestRevision || this.revision;
  293. // comparing ObjectId with string
  294. // eslint-disable-next-line eqeqeq
  295. if (revision != previousRevision) {
  296. return false;
  297. }
  298. return true;
  299. };
  300. pageSchema.methods.isLiked = function(userData) {
  301. return this.liker.some((likedUser) => {
  302. return likedUser === userData._id.toString();
  303. });
  304. };
  305. pageSchema.methods.like = function(userData) {
  306. const self = this;
  307. return new Promise(((resolve, reject) => {
  308. const added = self.liker.addToSet(userData._id);
  309. if (added.length > 0) {
  310. self.save((err, data) => {
  311. if (err) {
  312. return reject(err);
  313. }
  314. debug('liker updated!', added);
  315. return resolve(data);
  316. });
  317. }
  318. else {
  319. debug('liker not updated');
  320. return reject(self);
  321. }
  322. }));
  323. };
  324. pageSchema.methods.unlike = function(userData, callback) {
  325. const self = this;
  326. return new Promise(((resolve, reject) => {
  327. const beforeCount = self.liker.length;
  328. self.liker.pull(userData._id);
  329. if (self.liker.length !== beforeCount) {
  330. self.save((err, data) => {
  331. if (err) {
  332. return reject(err);
  333. }
  334. return resolve(data);
  335. });
  336. }
  337. else {
  338. debug('liker not updated');
  339. return reject(self);
  340. }
  341. }));
  342. };
  343. pageSchema.methods.isSeenUser = function(userData) {
  344. return this.seenUsers.includes(userData._id);
  345. };
  346. pageSchema.methods.seen = async function(userData) {
  347. if (this.isSeenUser(userData)) {
  348. debug('seenUsers not updated');
  349. return this;
  350. }
  351. if (!userData || !userData._id) {
  352. throw new Error('User data is not valid');
  353. }
  354. const added = this.seenUsers.addToSet(userData);
  355. const saved = await this.save();
  356. debug('seenUsers updated!', added);
  357. return saved;
  358. };
  359. pageSchema.methods.getSlackChannel = function() {
  360. const extended = this.get('extended');
  361. if (!extended) {
  362. return '';
  363. }
  364. return extended.slack || '';
  365. };
  366. pageSchema.methods.updateSlackChannel = function(slackChannel) {
  367. const extended = this.extended;
  368. extended.slack = slackChannel;
  369. return this.updateExtended(extended);
  370. };
  371. pageSchema.methods.updateExtended = function(extended) {
  372. const page = this;
  373. page.extended = extended;
  374. return new Promise(((resolve, reject) => {
  375. return page.save((err, doc) => {
  376. if (err) {
  377. return reject(err);
  378. }
  379. return resolve(doc);
  380. });
  381. }));
  382. };
  383. pageSchema.methods.initLatestRevisionField = async function(revisionId) {
  384. this.latestRevision = this.revision;
  385. if (revisionId != null) {
  386. this.revision = revisionId;
  387. }
  388. };
  389. pageSchema.methods.populateDataToShowRevision = async function() {
  390. validateCrowi();
  391. const User = crowi.model('User');
  392. return populateDataToShowRevision(this, User.USER_PUBLIC_FIELDS, User.IMAGE_POPULATION)
  393. .execPopulate();
  394. };
  395. pageSchema.methods.populateDataToMakePresentation = async function(revisionId) {
  396. this.latestRevision = this.revision;
  397. if (revisionId != null) {
  398. this.revision = revisionId;
  399. }
  400. return this.populate('revision').execPopulate();
  401. };
  402. pageSchema.methods.applyScope = function(user, grant, grantUserGroupId) {
  403. this.grant = grant;
  404. // reset
  405. this.grantedUsers = [];
  406. this.grantedGroup = null;
  407. if (grant !== GRANT_PUBLIC && grant !== GRANT_USER_GROUP) {
  408. this.grantedUsers.push(user._id);
  409. }
  410. if (grant === GRANT_USER_GROUP) {
  411. this.grantedGroup = grantUserGroupId;
  412. }
  413. };
  414. pageSchema.statics.updateCommentCount = function(pageId) {
  415. validateCrowi();
  416. const self = this;
  417. const Comment = crowi.model('Comment');
  418. return Comment.countCommentByPageId(pageId)
  419. .then((count) => {
  420. self.update({ _id: pageId }, { commentCount: count }, {}, (err, data) => {
  421. if (err) {
  422. debug('Update commentCount Error', err);
  423. throw err;
  424. }
  425. return data;
  426. });
  427. });
  428. };
  429. pageSchema.statics.getGrantLabels = function() {
  430. const grantLabels = {};
  431. grantLabels[GRANT_PUBLIC] = 'Public'; // 公開
  432. grantLabels[GRANT_RESTRICTED] = 'Anyone with the link'; // リンクを知っている人のみ
  433. // grantLabels[GRANT_SPECIFIED] = 'Specified users only'; // 特定ユーザーのみ
  434. grantLabels[GRANT_USER_GROUP] = 'Only inside the group'; // 特定グループのみ
  435. grantLabels[GRANT_OWNER] = 'Just me'; // 自分のみ
  436. return grantLabels;
  437. };
  438. pageSchema.statics.getUserPagePath = function(user) {
  439. return `/user/${user.username}`;
  440. };
  441. pageSchema.statics.getDeletedPageName = function(path) {
  442. if (path.match('/')) {
  443. // eslint-disable-next-line no-param-reassign
  444. path = path.substr(1);
  445. }
  446. return `/trash/${path}`;
  447. };
  448. pageSchema.statics.getRevertDeletedPageName = function(path) {
  449. return path.replace('/trash', '');
  450. };
  451. pageSchema.statics.isDeletableName = function(path) {
  452. const notDeletable = [
  453. /^\/user\/[^/]+$/, // user page
  454. ];
  455. for (let i = 0; i < notDeletable.length; i++) {
  456. const pattern = notDeletable[i];
  457. if (path.match(pattern)) {
  458. return false;
  459. }
  460. }
  461. return true;
  462. };
  463. pageSchema.statics.isCreatableName = function(name) {
  464. const forbiddenPages = [
  465. /\^|\$|\*|\+|#|%/,
  466. /^\/-\/.*/,
  467. /^\/_r\/.*/,
  468. /^\/_apix?(\/.*)?/,
  469. /^\/?https?:\/\/.+$/, // avoid miss in renaming
  470. /\/{2,}/, // avoid miss in renaming
  471. /\s+\/\s+/, // avoid miss in renaming
  472. /.+\/edit$/,
  473. /.+\.md$/,
  474. /^\/(installer|register|login|logout|admin|me|files|trash|paste|comments)(\/.*|$)/,
  475. ];
  476. let isCreatable = true;
  477. forbiddenPages.forEach((page) => {
  478. const pageNameReg = new RegExp(page);
  479. if (name.match(pageNameReg)) {
  480. isCreatable = false;
  481. }
  482. });
  483. return isCreatable;
  484. };
  485. pageSchema.statics.fixToCreatableName = function(path) {
  486. return path
  487. .replace(/\/\//g, '/');
  488. };
  489. pageSchema.statics.updateRevision = function(pageId, revisionId, cb) {
  490. this.update({ _id: pageId }, { revision: revisionId }, {}, (err, data) => {
  491. cb(err, data);
  492. });
  493. };
  494. /**
  495. * return whether the user is accessible to the page
  496. * @param {string} id ObjectId
  497. * @param {User} user
  498. */
  499. pageSchema.statics.isAccessiblePageByViewer = async function(id, user) {
  500. const baseQuery = this.count({ _id: id });
  501. let userGroups = [];
  502. if (user != null) {
  503. validateCrowi();
  504. const UserGroupRelation = crowi.model('UserGroupRelation');
  505. userGroups = await UserGroupRelation.findAllUserGroupIdsRelatedToUser(user);
  506. }
  507. const queryBuilder = new PageQueryBuilder(baseQuery);
  508. queryBuilder.addConditionToFilteringByViewer(user, userGroups, true);
  509. const count = await queryBuilder.query.exec();
  510. return count > 0;
  511. };
  512. /**
  513. * @param {string} id ObjectId
  514. * @param {User} user User instance
  515. * @param {UserGroup[]} userGroups List of UserGroup instances
  516. */
  517. pageSchema.statics.findByIdAndViewer = async function(id, user, userGroups) {
  518. const baseQuery = this.findOne({ _id: id });
  519. let relatedUserGroups = userGroups;
  520. if (user != null && relatedUserGroups == null) {
  521. validateCrowi();
  522. const UserGroupRelation = crowi.model('UserGroupRelation');
  523. relatedUserGroups = await UserGroupRelation.findAllUserGroupIdsRelatedToUser(user);
  524. }
  525. const queryBuilder = new PageQueryBuilder(baseQuery);
  526. queryBuilder.addConditionToFilteringByViewer(user, relatedUserGroups, true);
  527. return await queryBuilder.query.exec();
  528. };
  529. // find page by path
  530. pageSchema.statics.findByPath = function(path) {
  531. if (path == null) {
  532. return null;
  533. }
  534. return this.findOne({ path });
  535. };
  536. /**
  537. * @param {string} path Page path
  538. * @param {User} user User instance
  539. * @param {UserGroup[]} userGroups List of UserGroup instances
  540. */
  541. pageSchema.statics.findByPathAndViewer = async function(path, user, userGroups) {
  542. if (path == null) {
  543. throw new Error('path is required.');
  544. }
  545. const baseQuery = this.findOne({ path });
  546. let relatedUserGroups = userGroups;
  547. if (user != null && relatedUserGroups == null) {
  548. validateCrowi();
  549. const UserGroupRelation = crowi.model('UserGroupRelation');
  550. relatedUserGroups = await UserGroupRelation.findAllUserGroupIdsRelatedToUser(user);
  551. }
  552. const queryBuilder = new PageQueryBuilder(baseQuery);
  553. queryBuilder.addConditionToFilteringByViewer(user, relatedUserGroups, true);
  554. return await queryBuilder.query.exec();
  555. };
  556. /**
  557. * @param {string} path Page path
  558. * @param {User} user User instance
  559. * @param {UserGroup[]} userGroups List of UserGroup instances
  560. */
  561. pageSchema.statics.findAncestorByPathAndViewer = async function(path, user, userGroups) {
  562. if (path == null) {
  563. throw new Error('path is required.');
  564. }
  565. if (path === '/') {
  566. return null;
  567. }
  568. const ancestorsPaths = extractToAncestorsPaths(path);
  569. // pick the longest one
  570. const baseQuery = this.findOne({ path: { $in: ancestorsPaths } }).sort({ path: -1 });
  571. let relatedUserGroups = userGroups;
  572. if (user != null && relatedUserGroups == null) {
  573. validateCrowi();
  574. const UserGroupRelation = crowi.model('UserGroupRelation');
  575. relatedUserGroups = await UserGroupRelation.findAllUserGroupIdsRelatedToUser(user);
  576. }
  577. const queryBuilder = new PageQueryBuilder(baseQuery);
  578. queryBuilder.addConditionToFilteringByViewer(user, relatedUserGroups);
  579. return await queryBuilder.query.exec();
  580. };
  581. pageSchema.statics.findByRedirectTo = function(path) {
  582. return this.findOne({ redirectTo: path });
  583. };
  584. /**
  585. * find pages that is match with `path` and its descendants
  586. */
  587. pageSchema.statics.findListWithDescendants = async function(path, user, option) {
  588. const builder = new PageQueryBuilder(this.find());
  589. builder.addConditionToListWithDescendants(path, option);
  590. return await findListFromBuilderAndViewer(builder, user, false, option);
  591. };
  592. /**
  593. * find pages that start with `path`
  594. */
  595. pageSchema.statics.findListByStartWith = async function(path, user, option) {
  596. const builder = new PageQueryBuilder(this.find());
  597. builder.addConditionToListByStartWith(path, option);
  598. return await findListFromBuilderAndViewer(builder, user, false, option);
  599. };
  600. /**
  601. * find pages that is created by targetUser
  602. *
  603. * @param {User} targetUser
  604. * @param {User} currentUser
  605. * @param {any} option
  606. */
  607. pageSchema.statics.findListByCreator = async function(targetUser, currentUser, option) {
  608. const opt = Object.assign({ sort: 'createdAt', desc: -1 }, option);
  609. const builder = new PageQueryBuilder(this.find({ creator: targetUser._id }));
  610. let showAnyoneKnowsLink = null;
  611. if (targetUser != null && currentUser != null) {
  612. showAnyoneKnowsLink = targetUser._id.equals(currentUser._id);
  613. }
  614. return await findListFromBuilderAndViewer(builder, currentUser, showAnyoneKnowsLink, opt);
  615. };
  616. pageSchema.statics.findListByPageIds = async function(ids, option) {
  617. const User = crowi.model('User');
  618. const opt = Object.assign({}, option);
  619. const builder = new PageQueryBuilder(this.find({ _id: { $in: ids } }));
  620. builder.addConditionToExcludeRedirect();
  621. builder.addConditionToPagenate(opt.offset, opt.limit);
  622. // count
  623. const totalCount = await builder.query.exec('count');
  624. // find
  625. builder.populateDataToList(User.USER_PUBLIC_FIELDS, User.IMAGE_POPULATION);
  626. const pages = await builder.query.exec('find');
  627. const result = {
  628. pages, totalCount, offset: opt.offset, limit: opt.limit,
  629. };
  630. return result;
  631. };
  632. /**
  633. * find pages by PageQueryBuilder
  634. * @param {PageQueryBuilder} builder
  635. * @param {User} user
  636. * @param {boolean} showAnyoneKnowsLink
  637. * @param {any} option
  638. */
  639. async function findListFromBuilderAndViewer(builder, user, showAnyoneKnowsLink, option) {
  640. validateCrowi();
  641. const User = crowi.model('User');
  642. const opt = Object.assign({ sort: 'updatedAt', desc: -1 }, option);
  643. const sortOpt = {};
  644. sortOpt[opt.sort] = opt.desc;
  645. // exclude trashed pages
  646. if (!opt.includeTrashed) {
  647. builder.addConditionToExcludeTrashed();
  648. }
  649. // exclude redirect pages
  650. if (!opt.includeRedirect) {
  651. builder.addConditionToExcludeRedirect();
  652. }
  653. // add grant conditions
  654. await addConditionToFilteringByViewerForList(builder, user, showAnyoneKnowsLink);
  655. // count
  656. const totalCount = await builder.query.exec('count');
  657. // find
  658. builder.addConditionToPagenate(opt.offset, opt.limit, sortOpt);
  659. builder.populateDataToList(User.USER_PUBLIC_FIELDS, User.IMAGE_POPULATION);
  660. const pages = await builder.query.exec('find');
  661. const result = {
  662. pages, totalCount, offset: opt.offset, limit: opt.limit,
  663. };
  664. return result;
  665. }
  666. /**
  667. * Add condition that filter pages by viewer
  668. * by considering Config
  669. *
  670. * @param {PageQueryBuilder} builder
  671. * @param {User} user
  672. * @param {boolean} showAnyoneKnowsLink
  673. */
  674. async function addConditionToFilteringByViewerForList(builder, user, showAnyoneKnowsLink) {
  675. validateCrowi();
  676. const Config = crowi.model('Config');
  677. const config = crowi.getConfig();
  678. // determine User condition
  679. const hidePagesRestrictedByOwner = Config.hidePagesRestrictedByOwnerInList(config);
  680. const hidePagesRestrictedByGroup = Config.hidePagesRestrictedByGroupInList(config);
  681. // determine UserGroup condition
  682. let userGroups = null;
  683. if (user != null) {
  684. const UserGroupRelation = crowi.model('UserGroupRelation');
  685. userGroups = await UserGroupRelation.findAllUserGroupIdsRelatedToUser(user);
  686. }
  687. return builder.addConditionToFilteringByViewer(user, userGroups, showAnyoneKnowsLink, !hidePagesRestrictedByOwner, !hidePagesRestrictedByGroup);
  688. }
  689. /**
  690. * export addConditionToFilteringByViewerForList as static method
  691. */
  692. pageSchema.statics.addConditionToFilteringByViewerForList = addConditionToFilteringByViewerForList;
  693. /**
  694. * Throw error for growi-lsx-plugin (v1.x)
  695. */
  696. pageSchema.statics.generateQueryToListByStartWith = function(path, user, option) {
  697. const dummyQuery = this.find();
  698. dummyQuery.exec = async() => {
  699. throw new Error('Plugin version mismatch. Upgrade growi-lsx-plugin to v2.0.0 or above.');
  700. };
  701. return dummyQuery;
  702. };
  703. pageSchema.statics.generateQueryToListWithDescendants = pageSchema.statics.generateQueryToListByStartWith;
  704. /**
  705. * find all templates applicable to the new page
  706. */
  707. pageSchema.statics.findTemplate = function(path) {
  708. const templatePath = nodePath.posix.dirname(path);
  709. const pathList = generatePathsOnTree(path, []);
  710. const regexpList = pathList.map((path) => { return new RegExp(`^${escapeStringRegexp(path)}/_{1,2}template$`) });
  711. return this
  712. .find({ path: { $in: regexpList } })
  713. .populate({ path: 'revision', model: 'Revision' })
  714. .then((templates) => {
  715. return fetchTemplate(templates, templatePath);
  716. });
  717. };
  718. const generatePathsOnTree = (path, pathList) => {
  719. pathList.push(path);
  720. if (path === '/') {
  721. return pathList;
  722. }
  723. const newPath = nodePath.posix.dirname(path);
  724. return generatePathsOnTree(newPath, pathList);
  725. };
  726. const assignTemplateByType = (templates, path, type) => {
  727. for (let i = 0; i < templates.length; i++) {
  728. if (templates[i].path === `${path}/${type}template`) {
  729. return templates[i];
  730. }
  731. }
  732. };
  733. const assignDecendantsTemplate = (decendantsTemplates, path) => {
  734. const decendantsTemplate = assignTemplateByType(decendantsTemplates, path, '__');
  735. if (decendantsTemplate) {
  736. return decendantsTemplate;
  737. }
  738. if (path === '/') {
  739. return;
  740. }
  741. const newPath = nodePath.posix.dirname(path);
  742. return assignDecendantsTemplate(decendantsTemplates, newPath);
  743. };
  744. const fetchTemplate = (templates, templatePath) => {
  745. let templateBody;
  746. /**
  747. * get children template
  748. * __tempate: applicable only to immediate decendants
  749. */
  750. const childrenTemplate = assignTemplateByType(templates, templatePath, '_');
  751. /**
  752. * get decendants templates
  753. * _tempate: applicable to all pages under
  754. */
  755. const decendantsTemplate = assignDecendantsTemplate(templates, templatePath);
  756. if (childrenTemplate) {
  757. templateBody = childrenTemplate.revision.body;
  758. }
  759. else if (decendantsTemplate) {
  760. templateBody = decendantsTemplate.revision.body;
  761. }
  762. return templateBody;
  763. };
  764. /**
  765. * Bulk get (for internal only)
  766. */
  767. pageSchema.statics.getStreamOfFindAll = function(options) {
  768. const criteria = { redirectTo: null };
  769. return this.find(criteria)
  770. .populate([
  771. { path: 'creator', model: 'User' },
  772. { path: 'revision', model: 'Revision' },
  773. ])
  774. .lean()
  775. .cursor();
  776. };
  777. async function pushRevision(pageData, newRevision, user, grant, grantUserGroupId) {
  778. await newRevision.save();
  779. debug('Successfully saved new revision', newRevision);
  780. pageData.revision = newRevision;
  781. pageData.lastUpdateUser = user;
  782. pageData.updatedAt = Date.now();
  783. return pageData.save();
  784. }
  785. async function validateAppliedScope(user, grant, grantUserGroupId) {
  786. if (grant === GRANT_USER_GROUP && grantUserGroupId == null) {
  787. throw new Error('grant userGroupId is not specified');
  788. }
  789. if (grant === GRANT_USER_GROUP) {
  790. const UserGroupRelation = crowi.model('UserGroupRelation');
  791. const count = await UserGroupRelation.countByGroupIdAndUser(grantUserGroupId, user);
  792. if (count === 0) {
  793. throw new Error('no relations were exist for group and user.');
  794. }
  795. }
  796. }
  797. pageSchema.statics.create = async function(path, body, user, options = {}) {
  798. validateCrowi();
  799. const Page = this;
  800. const Revision = crowi.model('Revision');
  801. const format = options.format || 'markdown';
  802. const redirectTo = options.redirectTo || null;
  803. const grantUserGroupId = options.grantUserGroupId || null;
  804. const socketClientId = options.socketClientId || null;
  805. const tags = options.tags || null;
  806. // sanitize path
  807. path = crowi.xss.process(path); // eslint-disable-line no-param-reassign
  808. let grant = options.grant || GRANT_PUBLIC;
  809. // force public
  810. if (isPortalPath(path)) {
  811. grant = GRANT_PUBLIC;
  812. }
  813. const isExist = await this.count({ path });
  814. if (isExist) {
  815. throw new Error('Cannot create new page to existed path');
  816. }
  817. const page = new Page();
  818. page.path = path;
  819. page.creator = user;
  820. page.lastUpdateUser = user;
  821. page.redirectTo = redirectTo;
  822. page.status = STATUS_PUBLISHED;
  823. await validateAppliedScope(user, grant, grantUserGroupId);
  824. page.applyScope(user, grant, grantUserGroupId);
  825. page.updateTags(tags);
  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. };