page.js 41 KB

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