page.js 41 KB

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