page.js 42 KB

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