page.js 40 KB

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