page.js 41 KB

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