page.js 41 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396
  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(pageData, user, options = {}) {
  974. const path = pageData.path;
  975. const findOpts = { includeRedirect: true, includeTrashed: true };
  976. const result = await this.findListWithDescendants(path, user, findOpts);
  977. const pages = result.pages;
  978. await Promise.all(pages.map((page) => {
  979. return this.completelyDeletePage(page, user, options);
  980. }));
  981. return pageData;
  982. };
  983. pageSchema.statics.removeByPath = function(path) {
  984. if (path == null) {
  985. throw new Error('path is required');
  986. }
  987. return this.findOneAndRemove({ path }).exec();
  988. };
  989. /**
  990. * remove the page that is redirecting to specified `pagePath` recursively
  991. * ex: when
  992. * '/page1' redirects to '/page2' and
  993. * '/page2' redirects to '/page3'
  994. * and given '/page3',
  995. * '/page1' and '/page2' will be removed
  996. *
  997. * @param {string} pagePath
  998. */
  999. pageSchema.statics.removeRedirectOriginPageByPath = async function(pagePath) {
  1000. const redirectPage = await this.findByRedirectTo(pagePath);
  1001. if (redirectPage == null) {
  1002. return;
  1003. }
  1004. // remove
  1005. await this.findByIdAndRemove(redirectPage.id);
  1006. // remove recursive
  1007. await this.removeRedirectOriginPageByPath(redirectPage.path);
  1008. };
  1009. pageSchema.statics.rename = async function(pageData, newPagePath, user, options) {
  1010. validateCrowi();
  1011. const Page = this;
  1012. const Revision = crowi.model('Revision');
  1013. const path = pageData.path;
  1014. const createRedirectPage = options.createRedirectPage || false;
  1015. const updateMetadata = options.updateMetadata || false;
  1016. const socketClientId = options.socketClientId || null;
  1017. // sanitize path
  1018. newPagePath = crowi.xss.process(newPagePath); // eslint-disable-line no-param-reassign
  1019. // update Page
  1020. pageData.path = newPagePath;
  1021. if (updateMetadata) {
  1022. pageData.lastUpdateUser = user;
  1023. pageData.updatedAt = Date.now();
  1024. }
  1025. const updatedPageData = await pageData.save();
  1026. // update Rivisions
  1027. await Revision.updateRevisionListByPath(path, { path: newPagePath }, {});
  1028. if (createRedirectPage) {
  1029. const body = `redirect ${newPagePath}`;
  1030. await Page.create(path, body, user, { redirectTo: newPagePath });
  1031. }
  1032. pageEvent.emit('delete', pageData, user, socketClientId);
  1033. pageEvent.emit('create', updatedPageData, user, socketClientId);
  1034. return updatedPageData;
  1035. };
  1036. pageSchema.statics.renameRecursively = async function(pageData, newPagePathPrefix, user, options) {
  1037. validateCrowi();
  1038. const path = pageData.path;
  1039. const pathRegExp = new RegExp(`^${escapeStringRegexp(path)}`, 'i');
  1040. // sanitize path
  1041. newPagePathPrefix = crowi.xss.process(newPagePathPrefix); // eslint-disable-line no-param-reassign
  1042. const result = await this.findListWithDescendants(path, user, options);
  1043. await Promise.all(result.pages.map((page) => {
  1044. const newPagePath = page.path.replace(pathRegExp, newPagePathPrefix);
  1045. return this.rename(page, newPagePath, user, options);
  1046. }));
  1047. pageData.path = newPagePathPrefix;
  1048. return pageData;
  1049. };
  1050. pageSchema.statics.handlePrivatePagesForDeletedGroup = async function(deletedGroup, action, transferToUserGroupId) {
  1051. const Page = mongoose.model('Page');
  1052. const pages = await this.find({ grantedGroup: deletedGroup });
  1053. switch (action) {
  1054. case 'public':
  1055. await Promise.all(pages.map((page) => {
  1056. return Page.publicizePage(page);
  1057. }));
  1058. break;
  1059. case 'delete':
  1060. await Promise.all(pages.map((page) => {
  1061. return Page.completelyDeletePage(page);
  1062. }));
  1063. break;
  1064. case 'transfer':
  1065. await Promise.all(pages.map((page) => {
  1066. return Page.transferPageToGroup(page, transferToUserGroupId);
  1067. }));
  1068. break;
  1069. default:
  1070. throw new Error('Unknown action for private pages');
  1071. }
  1072. };
  1073. pageSchema.statics.publicizePage = async function(page) {
  1074. page.grantedGroup = null;
  1075. page.grant = GRANT_PUBLIC;
  1076. await page.save();
  1077. };
  1078. pageSchema.statics.transferPageToGroup = async function(page, transferToUserGroupId) {
  1079. const UserGroup = mongoose.model('UserGroup');
  1080. // check page existence
  1081. const isExist = await UserGroup.count({ _id: transferToUserGroupId }) > 0;
  1082. if (isExist) {
  1083. page.grantedGroup = transferToUserGroupId;
  1084. await page.save();
  1085. }
  1086. else {
  1087. throw new Error('Cannot find the group to which private pages belong to. _id: ', transferToUserGroupId);
  1088. }
  1089. };
  1090. /**
  1091. * associate GROWI page and HackMD page
  1092. * @param {Page} pageData
  1093. * @param {string} pageIdOnHackmd
  1094. */
  1095. pageSchema.statics.registerHackmdPage = function(pageData, pageIdOnHackmd) {
  1096. pageData.pageIdOnHackmd = pageIdOnHackmd;
  1097. return this.syncRevisionToHackmd(pageData);
  1098. };
  1099. /**
  1100. * update revisionHackmdSynced
  1101. * @param {Page} pageData
  1102. * @param {bool} isSave whether save or not
  1103. */
  1104. pageSchema.statics.syncRevisionToHackmd = function(pageData, isSave = true) {
  1105. pageData.revisionHackmdSynced = pageData.revision;
  1106. pageData.hasDraftOnHackmd = false;
  1107. let returnData = pageData;
  1108. if (isSave) {
  1109. returnData = pageData.save();
  1110. }
  1111. return returnData;
  1112. };
  1113. /**
  1114. * update hasDraftOnHackmd
  1115. * !! This will be invoked many time from many people !!
  1116. *
  1117. * @param {Page} pageData
  1118. * @param {Boolean} newValue
  1119. */
  1120. pageSchema.statics.updateHasDraftOnHackmd = async function(pageData, newValue) {
  1121. if (pageData.hasDraftOnHackmd === newValue) {
  1122. // do nothing when hasDraftOnHackmd equals to newValue
  1123. return;
  1124. }
  1125. pageData.hasDraftOnHackmd = newValue;
  1126. return pageData.save();
  1127. };
  1128. pageSchema.statics.getHistories = function() {
  1129. // TODO
  1130. };
  1131. /**
  1132. * return path that added slash to the end for specified path
  1133. */
  1134. pageSchema.statics.addSlashOfEnd = function(path) {
  1135. return addSlashOfEnd(path);
  1136. };
  1137. pageSchema.statics.GRANT_PUBLIC = GRANT_PUBLIC;
  1138. pageSchema.statics.GRANT_RESTRICTED = GRANT_RESTRICTED;
  1139. pageSchema.statics.GRANT_SPECIFIED = GRANT_SPECIFIED;
  1140. pageSchema.statics.GRANT_OWNER = GRANT_OWNER;
  1141. pageSchema.statics.GRANT_USER_GROUP = GRANT_USER_GROUP;
  1142. pageSchema.statics.PAGE_GRANT_ERROR = PAGE_GRANT_ERROR;
  1143. pageSchema.statics.PageQueryBuilder = PageQueryBuilder;
  1144. return mongoose.model('Page', pageSchema);
  1145. };