page.js 41 KB

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