page.js 41 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397
  1. // disable no-return-await for model functions
  2. /* eslint-disable no-return-await */
  3. /* eslint-disable no-use-before-define */
  4. const debug = require('debug')('growi:models:page');
  5. const nodePath = require('path');
  6. const mongoose = require('mongoose');
  7. const uniqueValidator = require('mongoose-unique-validator');
  8. const ObjectId = mongoose.Schema.Types.ObjectId;
  9. const escapeStringRegexp = require('escape-string-regexp');
  10. const templateChecker = require('@commons/util/template-checker');
  11. /*
  12. * define schema
  13. */
  14. const GRANT_PUBLIC = 1;
  15. const GRANT_RESTRICTED = 2;
  16. const GRANT_SPECIFIED = 3;
  17. const GRANT_OWNER = 4;
  18. const GRANT_USER_GROUP = 5;
  19. const PAGE_GRANT_ERROR = 1;
  20. const STATUS_PUBLISHED = 'published';
  21. const STATUS_DELETED = 'deleted';
  22. const pageSchema = new mongoose.Schema({
  23. path: {
  24. type: String, required: true, index: true, unique: true,
  25. },
  26. revision: { type: ObjectId, ref: 'Revision' },
  27. redirectTo: { type: String, index: true },
  28. status: { type: String, default: STATUS_PUBLISHED, index: true },
  29. grant: { type: Number, default: GRANT_PUBLIC, index: true },
  30. grantedUsers: [{ type: ObjectId, ref: 'User' }],
  31. grantedGroup: { type: ObjectId, ref: 'UserGroup', index: true },
  32. creator: { type: ObjectId, ref: 'User', index: true },
  33. lastUpdateUser: { type: ObjectId, ref: 'User', index: true },
  34. liker: [{ type: ObjectId, ref: 'User', index: true }],
  35. seenUsers: [{ type: ObjectId, ref: 'User', index: true }],
  36. commentCount: { type: Number, default: 0 },
  37. extended: {
  38. type: String,
  39. default: '{}',
  40. get(data) {
  41. try {
  42. return JSON.parse(data);
  43. }
  44. catch (e) {
  45. return data;
  46. }
  47. },
  48. set(data) {
  49. return JSON.stringify(data);
  50. },
  51. },
  52. pageIdOnHackmd: String,
  53. revisionHackmdSynced: { type: ObjectId, ref: 'Revision' }, // the revision that is synced to HackMD
  54. hasDraftOnHackmd: { type: Boolean }, // set true if revision and revisionHackmdSynced are same but HackMD document has modified
  55. createdAt: { type: Date, default: Date.now },
  56. updatedAt: { type: Date, default: Date.now },
  57. }, {
  58. toJSON: { getters: true },
  59. toObject: { getters: true },
  60. });
  61. // apply plugins
  62. pageSchema.plugin(uniqueValidator);
  63. /**
  64. * return an array of ancestors paths that is extracted from specified pagePath
  65. * e.g.
  66. * when `pagePath` is `/foo/bar/baz`,
  67. * this method returns [`/foo/bar/baz`, `/foo/bar`, `/foo`, `/`]
  68. *
  69. * @param {string} pagePath
  70. * @return {string[]} ancestors paths
  71. */
  72. const extractToAncestorsPaths = (pagePath) => {
  73. const ancestorsPaths = [];
  74. let parentPath;
  75. while (parentPath !== '/') {
  76. parentPath = nodePath.dirname(parentPath || pagePath);
  77. ancestorsPaths.push(parentPath);
  78. }
  79. return ancestorsPaths;
  80. };
  81. const addSlashOfEnd = (path) => {
  82. let returnPath = path;
  83. if (!path.match(/\/$/)) {
  84. returnPath += '/';
  85. }
  86. return returnPath;
  87. };
  88. /**
  89. * populate page (Query or Document) to show revision
  90. * @param {any} page Query or Document
  91. * @param {string} userPublicFields string to set to select
  92. */
  93. /* eslint-disable object-curly-newline, object-property-newline */
  94. const populateDataToShowRevision = (page, userPublicFields, imagePopulation) => {
  95. return page
  96. .populate([
  97. { path: 'lastUpdateUser', model: 'User', select: userPublicFields, populate: imagePopulation },
  98. { path: 'creator', model: 'User', select: userPublicFields, populate: imagePopulation },
  99. { path: 'grantedGroup', model: 'UserGroup' },
  100. { path: 'revision', model: 'Revision', populate: {
  101. path: 'author', model: 'User', select: userPublicFields, populate: imagePopulation,
  102. } },
  103. ]);
  104. };
  105. /* eslint-enable object-curly-newline, object-property-newline */
  106. class PageQueryBuilder {
  107. constructor(query) {
  108. this.query = query;
  109. }
  110. addConditionToExcludeTrashed() {
  111. this.query = this.query
  112. .and({
  113. $or: [
  114. { status: null },
  115. { status: STATUS_PUBLISHED },
  116. ],
  117. });
  118. return this;
  119. }
  120. addConditionToExcludeRedirect() {
  121. this.query = this.query.and({ redirectTo: null });
  122. return this;
  123. }
  124. /**
  125. * generate the query to find the page that is match with `path` and its descendants
  126. */
  127. addConditionToListWithDescendants(path, option) {
  128. // ignore other pages than descendants
  129. // eslint-disable-next-line no-param-reassign
  130. path = addSlashOfEnd(path);
  131. // add option to escape the regex strings
  132. const combinedOption = Object.assign({ isRegExpEscapedFromPath: true }, option);
  133. this.addConditionToListByStartWith(path, combinedOption);
  134. return this;
  135. }
  136. /**
  137. * generate the query to find pages that start with `path`
  138. *
  139. * (GROWI) If 'isRegExpEscapedFromPath' is true, `path` should have `/` at the end
  140. * -> returns '{path}/*' and '{path}' self.
  141. * (Crowi) If 'isRegExpEscapedFromPath' is false and `path` has `/` at the end
  142. * -> returns '{path}*'
  143. * (Crowi) If 'isRegExpEscapedFromPath' is false and `path` doesn't have `/` at the end
  144. * -> returns '{path}*'
  145. *
  146. * *option*
  147. * - isRegExpEscapedFromPath -- if true, the regex strings included in `path` is escaped (default: false)
  148. */
  149. addConditionToListByStartWith(path, option) {
  150. const pathCondition = [];
  151. const isRegExpEscapedFromPath = option.isRegExpEscapedFromPath || false;
  152. /*
  153. * 1. add condition for finding the page completely match with `path` w/o last slash
  154. */
  155. let pathSlashOmitted = path;
  156. if (path.match(/\/$/)) {
  157. pathSlashOmitted = path.substr(0, path.length - 1);
  158. pathCondition.push({ path: pathSlashOmitted });
  159. }
  160. /*
  161. * 2. add decendants
  162. */
  163. const pattern = (isRegExpEscapedFromPath)
  164. ? escapeStringRegexp(path) // escape
  165. : pathSlashOmitted;
  166. let queryReg;
  167. try {
  168. queryReg = new RegExp(`^${pattern}`);
  169. }
  170. // if regular expression is invalid
  171. catch (e) {
  172. // force to escape
  173. queryReg = new RegExp(`^${escapeStringRegexp(pattern)}`);
  174. }
  175. pathCondition.push({ path: queryReg });
  176. this.query = this.query
  177. .and({
  178. $or: pathCondition,
  179. });
  180. return this;
  181. }
  182. addConditionToFilteringByViewer(user, userGroups, showAnyoneKnowsLink, showPagesRestrictedByOwner, showPagesRestrictedByGroup) {
  183. const grantConditions = [
  184. { grant: null },
  185. { grant: GRANT_PUBLIC },
  186. ];
  187. if (showAnyoneKnowsLink) {
  188. grantConditions.push({ grant: GRANT_RESTRICTED });
  189. }
  190. if (showPagesRestrictedByOwner) {
  191. grantConditions.push(
  192. { grant: GRANT_SPECIFIED },
  193. { grant: GRANT_OWNER },
  194. );
  195. }
  196. else if (user != null) {
  197. grantConditions.push(
  198. { grant: GRANT_SPECIFIED, grantedUsers: user._id },
  199. { grant: GRANT_OWNER, grantedUsers: user._id },
  200. );
  201. }
  202. if (showPagesRestrictedByGroup) {
  203. grantConditions.push(
  204. { grant: GRANT_USER_GROUP },
  205. );
  206. }
  207. else if (userGroups != null && userGroups.length > 0) {
  208. grantConditions.push(
  209. { grant: GRANT_USER_GROUP, grantedGroup: { $in: userGroups } },
  210. );
  211. }
  212. this.query = this.query
  213. .and({
  214. $or: grantConditions,
  215. });
  216. return this;
  217. }
  218. addConditionToPagenate(offset, limit, sortOpt) {
  219. this.query = this.query
  220. .sort(sortOpt).skip(offset).limit(limit); // eslint-disable-line newline-per-chained-call
  221. return this;
  222. }
  223. populateDataToList(userPublicFields, imagePopulation) {
  224. this.query = this.query
  225. .populate({
  226. path: 'lastUpdateUser',
  227. select: userPublicFields,
  228. populate: imagePopulation,
  229. });
  230. return this;
  231. }
  232. populateDataToShowRevision(userPublicFields, imagePopulation) {
  233. this.query = populateDataToShowRevision(this.query, userPublicFields, imagePopulation);
  234. return this;
  235. }
  236. }
  237. module.exports = function(crowi) {
  238. const { configManager } = 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 isPortalPath(path) {
  247. if (path.match(/.*\/$/)) {
  248. return true;
  249. }
  250. return false;
  251. }
  252. function validateCrowi() {
  253. if (crowi == null) {
  254. throw new Error('"crowi" is null. Init User model with "crowi" argument first.');
  255. }
  256. }
  257. pageSchema.methods.isDeleted = function() {
  258. return (this.status === STATUS_DELETED) || checkIfTrashed(this.path);
  259. };
  260. pageSchema.methods.isPublic = function() {
  261. if (!this.grant || this.grant === GRANT_PUBLIC) {
  262. return true;
  263. }
  264. return false;
  265. };
  266. pageSchema.methods.isPortal = function() {
  267. return isPortalPath(this.path);
  268. };
  269. pageSchema.methods.isTemplate = function() {
  270. return templateChecker(this.path);
  271. };
  272. pageSchema.methods.isLatestRevision = function() {
  273. // populate されていなくて判断できない
  274. if (!this.latestRevision || !this.revision) {
  275. return true;
  276. }
  277. // comparing ObjectId with string
  278. // eslint-disable-next-line eqeqeq
  279. return (this.latestRevision == this.revision._id.toString());
  280. };
  281. pageSchema.methods.findRelatedTagsById = async function() {
  282. const PageTagRelation = mongoose.model('PageTagRelation');
  283. const relations = await PageTagRelation.find({ relatedPage: this._id }).populate('relatedTag');
  284. return relations.map((relation) => { return relation.relatedTag.name });
  285. };
  286. pageSchema.methods.isUpdatable = function(previousRevision) {
  287. const revision = this.latestRevision || this.revision;
  288. // comparing ObjectId with string
  289. // eslint-disable-next-line eqeqeq
  290. if (revision != previousRevision) {
  291. return false;
  292. }
  293. return true;
  294. };
  295. pageSchema.methods.isLiked = function(userData) {
  296. return this.liker.some((likedUserId) => {
  297. return likedUserId.toString() === userData._id.toString();
  298. });
  299. };
  300. pageSchema.methods.like = function(userData) {
  301. const self = this;
  302. return new Promise(((resolve, reject) => {
  303. const added = self.liker.addToSet(userData._id);
  304. if (added.length > 0) {
  305. self.save((err, data) => {
  306. if (err) {
  307. return reject(err);
  308. }
  309. debug('liker updated!', added);
  310. return resolve(data);
  311. });
  312. }
  313. else {
  314. this.logger.warn('liker not updated');
  315. return reject(self);
  316. }
  317. }));
  318. };
  319. pageSchema.methods.unlike = function(userData, callback) {
  320. const self = this;
  321. return new Promise(((resolve, reject) => {
  322. const beforeCount = self.liker.length;
  323. self.liker.pull(userData._id);
  324. if (self.liker.length !== beforeCount) {
  325. self.save((err, data) => {
  326. if (err) {
  327. return reject(err);
  328. }
  329. return resolve(data);
  330. });
  331. }
  332. else {
  333. debug('liker not updated');
  334. return reject(self);
  335. }
  336. }));
  337. };
  338. pageSchema.methods.isSeenUser = function(userData) {
  339. return this.seenUsers.includes(userData._id);
  340. };
  341. pageSchema.methods.seen = async function(userData) {
  342. if (this.isSeenUser(userData)) {
  343. debug('seenUsers not updated');
  344. return this;
  345. }
  346. if (!userData || !userData._id) {
  347. throw new Error('User data is not valid');
  348. }
  349. const added = this.seenUsers.addToSet(userData);
  350. const saved = await this.save();
  351. debug('seenUsers updated!', added);
  352. return saved;
  353. };
  354. pageSchema.methods.getSlackChannel = function() {
  355. const extended = this.get('extended');
  356. if (!extended) {
  357. return '';
  358. }
  359. return extended.slack || '';
  360. };
  361. pageSchema.methods.updateSlackChannel = function(slackChannel) {
  362. const extended = this.extended;
  363. extended.slack = slackChannel;
  364. return this.updateExtended(extended);
  365. };
  366. pageSchema.methods.updateExtended = function(extended) {
  367. const page = this;
  368. page.extended = extended;
  369. return new Promise(((resolve, reject) => {
  370. return page.save((err, doc) => {
  371. if (err) {
  372. return reject(err);
  373. }
  374. return resolve(doc);
  375. });
  376. }));
  377. };
  378. pageSchema.methods.initLatestRevisionField = async function(revisionId) {
  379. this.latestRevision = this.revision;
  380. if (revisionId != null) {
  381. this.revision = revisionId;
  382. }
  383. };
  384. pageSchema.methods.populateDataToShowRevision = async function() {
  385. validateCrowi();
  386. const User = crowi.model('User');
  387. return populateDataToShowRevision(this, User.USER_PUBLIC_FIELDS, User.IMAGE_POPULATION)
  388. .execPopulate();
  389. };
  390. pageSchema.methods.populateDataToMakePresentation = async function(revisionId) {
  391. this.latestRevision = this.revision;
  392. if (revisionId != null) {
  393. this.revision = revisionId;
  394. }
  395. return this.populate('revision').execPopulate();
  396. };
  397. pageSchema.methods.applyScope = function(user, grant, grantUserGroupId) {
  398. this.grant = grant;
  399. // reset
  400. this.grantedUsers = [];
  401. this.grantedGroup = null;
  402. if (grant !== GRANT_PUBLIC && grant !== GRANT_USER_GROUP) {
  403. this.grantedUsers.push(user._id);
  404. }
  405. if (grant === GRANT_USER_GROUP) {
  406. this.grantedGroup = grantUserGroupId;
  407. }
  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] = 'Just 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, User.IMAGE_POPULATION);
  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, User.IMAGE_POPULATION);
  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 = configManager.getCofnig('crowi', 'security:list-policy:hideRestrictedByOwner');
  673. const hidePagesRestrictedByGroup = configManager.getCofnig('crowi', 'security:list-policy:hidePagesRestrictedByGroupInList');
  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. * export addConditionToFilteringByViewerForList as static method
  684. */
  685. pageSchema.statics.addConditionToFilteringByViewerForList = addConditionToFilteringByViewerForList;
  686. /**
  687. * Throw error for growi-lsx-plugin (v1.x)
  688. */
  689. pageSchema.statics.generateQueryToListByStartWith = function(path, user, option) {
  690. const dummyQuery = this.find();
  691. dummyQuery.exec = async() => {
  692. throw new Error('Plugin version mismatch. Upgrade growi-lsx-plugin to v2.0.0 or above.');
  693. };
  694. return dummyQuery;
  695. };
  696. pageSchema.statics.generateQueryToListWithDescendants = pageSchema.statics.generateQueryToListByStartWith;
  697. /**
  698. * find all templates applicable to the new page
  699. */
  700. pageSchema.statics.findTemplate = function(path) {
  701. const templatePath = nodePath.posix.dirname(path);
  702. const pathList = generatePathsOnTree(path, []);
  703. const regexpList = pathList.map((path) => { return new RegExp(`^${escapeStringRegexp(path)}/_{1,2}template$`) });
  704. return this
  705. .find({ path: { $in: regexpList } })
  706. .populate({ path: 'revision', model: 'Revision' })
  707. .then((templates) => {
  708. return fetchTemplate(templates, templatePath);
  709. });
  710. };
  711. const generatePathsOnTree = (path, pathList) => {
  712. pathList.push(path);
  713. if (path === '/') {
  714. return pathList;
  715. }
  716. const newPath = nodePath.posix.dirname(path);
  717. return generatePathsOnTree(newPath, pathList);
  718. };
  719. const assignTemplateByType = (templates, path, type) => {
  720. for (let i = 0; i < templates.length; i++) {
  721. if (templates[i].path === `${path}/${type}template`) {
  722. return templates[i];
  723. }
  724. }
  725. };
  726. const assignDecendantsTemplate = (decendantsTemplates, path) => {
  727. const decendantsTemplate = assignTemplateByType(decendantsTemplates, path, '__');
  728. if (decendantsTemplate) {
  729. return decendantsTemplate;
  730. }
  731. if (path === '/') {
  732. return;
  733. }
  734. const newPath = nodePath.posix.dirname(path);
  735. return assignDecendantsTemplate(decendantsTemplates, newPath);
  736. };
  737. const fetchTemplate = async(templates, templatePath) => {
  738. let templateBody;
  739. let templateTags;
  740. /**
  741. * get children template
  742. * __tempate: applicable only to immediate decendants
  743. */
  744. const childrenTemplate = assignTemplateByType(templates, templatePath, '_');
  745. /**
  746. * get decendants templates
  747. * _tempate: applicable to all pages under
  748. */
  749. const decendantsTemplate = assignDecendantsTemplate(templates, templatePath);
  750. if (childrenTemplate) {
  751. templateBody = childrenTemplate.revision.body;
  752. templateTags = await childrenTemplate.findRelatedTagsById();
  753. }
  754. else if (decendantsTemplate) {
  755. templateBody = decendantsTemplate.revision.body;
  756. templateTags = await decendantsTemplate.findRelatedTagsById();
  757. }
  758. return { templateBody, templateTags };
  759. };
  760. /**
  761. * Bulk get (for internal only)
  762. */
  763. pageSchema.statics.getStreamOfFindAll = function(options) {
  764. const criteria = { redirectTo: null };
  765. return this.find(criteria)
  766. .populate([
  767. { path: 'creator', model: 'User' },
  768. { path: 'revision', model: 'Revision' },
  769. ])
  770. .lean()
  771. .cursor();
  772. };
  773. async function pushRevision(pageData, newRevision, user, grant, grantUserGroupId) {
  774. await newRevision.save();
  775. debug('Successfully saved new revision', newRevision);
  776. pageData.revision = newRevision;
  777. pageData.lastUpdateUser = user;
  778. pageData.updatedAt = Date.now();
  779. return pageData.save();
  780. }
  781. async function validateAppliedScope(user, grant, grantUserGroupId) {
  782. if (grant === GRANT_USER_GROUP && grantUserGroupId == null) {
  783. throw new Error('grant userGroupId is not specified');
  784. }
  785. if (grant === GRANT_USER_GROUP) {
  786. const UserGroupRelation = crowi.model('UserGroupRelation');
  787. const count = await UserGroupRelation.countByGroupIdAndUser(grantUserGroupId, user);
  788. if (count === 0) {
  789. throw new Error('no relations were exist for group and user.');
  790. }
  791. }
  792. }
  793. pageSchema.statics.create = async function(path, body, user, options = {}) {
  794. validateCrowi();
  795. const Page = this;
  796. const Revision = crowi.model('Revision');
  797. const format = options.format || 'markdown';
  798. const redirectTo = options.redirectTo || null;
  799. const grantUserGroupId = options.grantUserGroupId || null;
  800. const socketClientId = options.socketClientId || null;
  801. // sanitize path
  802. path = crowi.xss.process(path); // eslint-disable-line no-param-reassign
  803. let grant = options.grant || GRANT_PUBLIC;
  804. // force public
  805. if (isPortalPath(path)) {
  806. grant = GRANT_PUBLIC;
  807. }
  808. const isExist = await this.count({ path });
  809. if (isExist) {
  810. throw new Error('Cannot create new page to existed path');
  811. }
  812. const page = new Page();
  813. page.path = path;
  814. page.creator = user;
  815. page.lastUpdateUser = user;
  816. page.redirectTo = redirectTo;
  817. page.status = STATUS_PUBLISHED;
  818. await validateAppliedScope(user, grant, grantUserGroupId);
  819. page.applyScope(user, grant, grantUserGroupId);
  820. let savedPage = await page.save();
  821. const newRevision = Revision.prepareRevision(savedPage, body, null, user, { format });
  822. const revision = await pushRevision(savedPage, newRevision, user, grant, grantUserGroupId);
  823. savedPage = await this.findByPath(revision.path)
  824. .populate('revision')
  825. .populate('creator');
  826. if (socketClientId != null) {
  827. pageEvent.emit('create', savedPage, user, socketClientId);
  828. }
  829. return savedPage;
  830. };
  831. pageSchema.statics.updatePage = async function(pageData, body, previousBody, user, options = {}) {
  832. validateCrowi();
  833. const Revision = crowi.model('Revision');
  834. const grant = options.grant || null;
  835. const grantUserGroupId = options.grantUserGroupId || null;
  836. const isSyncRevisionToHackmd = options.isSyncRevisionToHackmd;
  837. const socketClientId = options.socketClientId || null;
  838. await validateAppliedScope(user, grant, grantUserGroupId);
  839. pageData.applyScope(user, grant, grantUserGroupId);
  840. // update existing page
  841. let savedPage = await pageData.save();
  842. const newRevision = await Revision.prepareRevision(pageData, body, previousBody, user);
  843. const revision = await pushRevision(savedPage, newRevision, user, grant, grantUserGroupId);
  844. savedPage = await this.findByPath(revision.path)
  845. .populate('revision')
  846. .populate('creator');
  847. if (isSyncRevisionToHackmd) {
  848. savedPage = await this.syncRevisionToHackmd(savedPage);
  849. }
  850. if (socketClientId != null) {
  851. pageEvent.emit('update', savedPage, user, socketClientId);
  852. }
  853. return savedPage;
  854. };
  855. pageSchema.statics.applyScopesToDescendantsAsyncronously = async function(parentPage, user) {
  856. const builder = new PageQueryBuilder(this.find());
  857. builder.addConditionToListWithDescendants(parentPage.path);
  858. builder.addConditionToExcludeRedirect();
  859. // add grant conditions
  860. await addConditionToFilteringByViewerForList(builder, user);
  861. // get all pages that the specified user can update
  862. const pages = await builder.query.exec();
  863. for (const page of pages) {
  864. // skip parentPage
  865. if (page.id === parentPage.id) {
  866. continue;
  867. }
  868. page.applyScope(user, parentPage.grant, parentPage.grantedGroup);
  869. page.save();
  870. }
  871. };
  872. pageSchema.statics.deletePage = async function(pageData, user, options = {}) {
  873. const newPath = this.getDeletedPageName(pageData.path);
  874. const isTrashed = checkIfTrashed(pageData.path);
  875. const socketClientId = options.socketClientId || null;
  876. if (this.isDeletableName(pageData.path)) {
  877. if (isTrashed) {
  878. return this.completelyDeletePage(pageData, user, options);
  879. }
  880. pageData.status = STATUS_DELETED;
  881. const updatedPageData = await this.rename(pageData, newPath, user, { socketClientId, createRedirectPage: true });
  882. return updatedPageData;
  883. }
  884. return Promise.reject(new Error('Page is not deletable.'));
  885. };
  886. const checkIfTrashed = (path) => {
  887. return (path.search(/^\/trash/) !== -1);
  888. };
  889. pageSchema.statics.deletePageRecursively = async function(targetPage, user, options = {}) {
  890. const isTrashed = checkIfTrashed(targetPage.path);
  891. if (isTrashed) {
  892. return this.completelyDeletePageRecursively(targetPage, user, options);
  893. }
  894. const findOpts = { includeRedirect: true };
  895. const result = await this.findListWithDescendants(targetPage.path, user, findOpts);
  896. const pages = result.pages;
  897. let updatedPage = null;
  898. await Promise.all(pages.map((page) => {
  899. const isParent = (page.path === targetPage.path);
  900. const p = this.deletePage(page, user, options);
  901. if (isParent) {
  902. updatedPage = p;
  903. }
  904. return p;
  905. }));
  906. return updatedPage;
  907. };
  908. pageSchema.statics.revertDeletedPage = async function(page, user, options = {}) {
  909. const newPath = this.getRevertDeletedPageName(page.path);
  910. const originPage = await this.findByPath(newPath);
  911. if (originPage != null) {
  912. // 削除時、元ページの path には必ず redirectTo 付きで、ページが作成される。
  913. // そのため、そいつは削除してOK
  914. // が、redirectTo ではないページが存在している場合それは何かがおかしい。(データ補正が必要)
  915. if (originPage.redirectTo !== page.path) {
  916. throw new Error('The new page of to revert is exists and the redirect path of the page is not the deleted page.');
  917. }
  918. await this.completelyDeletePage(originPage, options);
  919. }
  920. page.status = STATUS_PUBLISHED;
  921. page.lastUpdateUser = user;
  922. debug('Revert deleted the page', page, newPath);
  923. const updatedPage = await this.rename(page, newPath, user, {});
  924. return updatedPage;
  925. };
  926. pageSchema.statics.revertDeletedPageRecursively = async function(targetPage, user, options = {}) {
  927. const findOpts = { includeRedirect: true, includeTrashed: true };
  928. const result = await this.findListWithDescendants(targetPage.path, user, findOpts);
  929. const pages = result.pages;
  930. let updatedPage = null;
  931. await Promise.all(pages.map((page) => {
  932. const isParent = (page.path === targetPage.path);
  933. const p = this.revertDeletedPage(page, user, options);
  934. if (isParent) {
  935. updatedPage = p;
  936. }
  937. return p;
  938. }));
  939. return updatedPage;
  940. };
  941. /**
  942. * This is danger.
  943. */
  944. pageSchema.statics.completelyDeletePage = async function(pageData, user, options = {}) {
  945. validateCrowi();
  946. // Delete Bookmarks, Attachments, Revisions, Pages and emit delete
  947. const Bookmark = crowi.model('Bookmark');
  948. const Attachment = crowi.model('Attachment');
  949. const Comment = crowi.model('Comment');
  950. const Revision = crowi.model('Revision');
  951. const pageId = pageData._id;
  952. const socketClientId = options.socketClientId || null;
  953. debug('Completely delete', pageData.path);
  954. await Bookmark.removeBookmarksByPageId(pageId);
  955. await Attachment.removeAttachmentsByPageId(pageId);
  956. await Comment.removeCommentsByPageId(pageId);
  957. await Revision.removeRevisionsByPath(pageData.path);
  958. await this.findByIdAndRemove(pageId);
  959. await this.removeRedirectOriginPageByPath(pageData.path);
  960. if (socketClientId != null) {
  961. pageEvent.emit('delete', pageData, user, socketClientId); // update as renamed page
  962. }
  963. return pageData;
  964. };
  965. /**
  966. * Delete Bookmarks, Attachments, Revisions, Pages and emit delete
  967. */
  968. pageSchema.statics.completelyDeletePageRecursively = async function(pageData, user, options = {}) {
  969. const path = pageData.path;
  970. const findOpts = { includeRedirect: true, includeTrashed: true };
  971. const result = await this.findListWithDescendants(path, user, findOpts);
  972. const pages = result.pages;
  973. await Promise.all(pages.map((page) => {
  974. return this.completelyDeletePage(page, user, options);
  975. }));
  976. return pageData;
  977. };
  978. pageSchema.statics.removeByPath = function(path) {
  979. if (path == null) {
  980. throw new Error('path is required');
  981. }
  982. return this.findOneAndRemove({ path }).exec();
  983. };
  984. /**
  985. * remove the page that is redirecting to specified `pagePath` recursively
  986. * ex: when
  987. * '/page1' redirects to '/page2' and
  988. * '/page2' redirects to '/page3'
  989. * and given '/page3',
  990. * '/page1' and '/page2' will be removed
  991. *
  992. * @param {string} pagePath
  993. */
  994. pageSchema.statics.removeRedirectOriginPageByPath = async function(pagePath) {
  995. const redirectPage = await this.findByRedirectTo(pagePath);
  996. if (redirectPage == null) {
  997. return;
  998. }
  999. // remove
  1000. await this.findByIdAndRemove(redirectPage.id);
  1001. // remove recursive
  1002. await this.removeRedirectOriginPageByPath(redirectPage.path);
  1003. };
  1004. pageSchema.statics.rename = async function(pageData, newPagePath, user, options) {
  1005. validateCrowi();
  1006. const Page = this;
  1007. const Revision = crowi.model('Revision');
  1008. const path = pageData.path;
  1009. const createRedirectPage = options.createRedirectPage || 0;
  1010. const socketClientId = options.socketClientId || null;
  1011. // sanitize path
  1012. newPagePath = crowi.xss.process(newPagePath); // eslint-disable-line no-param-reassign
  1013. // update Page
  1014. pageData.path = newPagePath;
  1015. pageData.lastUpdateUser = user;
  1016. pageData.updatedAt = Date.now();
  1017. const updatedPageData = await pageData.save();
  1018. // update Rivisions
  1019. await Revision.updateRevisionListByPath(path, { path: newPagePath }, {});
  1020. if (createRedirectPage) {
  1021. const body = `redirect ${newPagePath}`;
  1022. await Page.create(path, body, user, { redirectTo: newPagePath });
  1023. }
  1024. pageEvent.emit('delete', pageData, user, socketClientId);
  1025. pageEvent.emit('create', updatedPageData, user, socketClientId);
  1026. return updatedPageData;
  1027. };
  1028. pageSchema.statics.renameRecursively = async function(pageData, newPagePathPrefix, user, options) {
  1029. validateCrowi();
  1030. const path = pageData.path;
  1031. const pathRegExp = new RegExp(`^${escapeStringRegexp(path)}`, 'i');
  1032. // sanitize path
  1033. newPagePathPrefix = crowi.xss.process(newPagePathPrefix); // eslint-disable-line no-param-reassign
  1034. const result = await this.findListWithDescendants(path, user, options);
  1035. await Promise.all(result.pages.map((page) => {
  1036. const newPagePath = page.path.replace(pathRegExp, newPagePathPrefix);
  1037. return this.rename(page, newPagePath, user, options);
  1038. }));
  1039. pageData.path = newPagePathPrefix;
  1040. return pageData;
  1041. };
  1042. pageSchema.statics.handlePrivatePagesForDeletedGroup = async function(deletedGroup, action, selectedGroupId) {
  1043. const Page = mongoose.model('Page');
  1044. const pages = await this.find({ grantedGroup: deletedGroup });
  1045. switch (action) {
  1046. case 'public':
  1047. await Promise.all(pages.map((page) => {
  1048. return Page.publicizePage(page);
  1049. }));
  1050. break;
  1051. case 'delete':
  1052. await Promise.all(pages.map((page) => {
  1053. return Page.completelyDeletePage(page);
  1054. }));
  1055. break;
  1056. case 'transfer':
  1057. await Promise.all(pages.map((page) => {
  1058. return Page.transferPageToGroup(page, selectedGroupId);
  1059. }));
  1060. break;
  1061. default:
  1062. throw new Error('Unknown action for private pages');
  1063. }
  1064. };
  1065. pageSchema.statics.publicizePage = async function(page) {
  1066. page.grantedGroup = null;
  1067. page.grant = GRANT_PUBLIC;
  1068. await page.save();
  1069. };
  1070. pageSchema.statics.transferPageToGroup = async function(page, selectedGroupId) {
  1071. const UserGroup = mongoose.model('UserGroup');
  1072. // check page existence
  1073. const isExist = await UserGroup.count({ _id: selectedGroupId }) > 0;
  1074. if (isExist) {
  1075. page.grantedGroup = selectedGroupId;
  1076. await page.save();
  1077. }
  1078. else {
  1079. throw new Error('Cannot find the group to which private pages belong to. _id: ', selectedGroupId);
  1080. }
  1081. };
  1082. /**
  1083. * associate GROWI page and HackMD page
  1084. * @param {Page} pageData
  1085. * @param {string} pageIdOnHackmd
  1086. */
  1087. pageSchema.statics.registerHackmdPage = function(pageData, pageIdOnHackmd) {
  1088. if (pageData.pageIdOnHackmd != null) {
  1089. throw new Error(`'pageIdOnHackmd' of the page '${pageData.path}' is not empty`);
  1090. }
  1091. pageData.pageIdOnHackmd = pageIdOnHackmd;
  1092. return this.syncRevisionToHackmd(pageData);
  1093. };
  1094. /**
  1095. * update revisionHackmdSynced
  1096. * @param {Page} pageData
  1097. * @param {bool} isSave whether save or not
  1098. */
  1099. pageSchema.statics.syncRevisionToHackmd = function(pageData, isSave = true) {
  1100. pageData.revisionHackmdSynced = pageData.revision;
  1101. pageData.hasDraftOnHackmd = false;
  1102. let returnData = pageData;
  1103. if (isSave) {
  1104. returnData = pageData.save();
  1105. }
  1106. return returnData;
  1107. };
  1108. /**
  1109. * update hasDraftOnHackmd
  1110. * !! This will be invoked many time from many people !!
  1111. *
  1112. * @param {Page} pageData
  1113. * @param {Boolean} newValue
  1114. */
  1115. pageSchema.statics.updateHasDraftOnHackmd = async function(pageData, newValue) {
  1116. if (pageData.hasDraftOnHackmd === newValue) {
  1117. // do nothing when hasDraftOnHackmd equals to newValue
  1118. return;
  1119. }
  1120. pageData.hasDraftOnHackmd = newValue;
  1121. return pageData.save();
  1122. };
  1123. pageSchema.statics.getHistories = function() {
  1124. // TODO
  1125. };
  1126. /**
  1127. * return path that added slash to the end for specified path
  1128. */
  1129. pageSchema.statics.addSlashOfEnd = function(path) {
  1130. return addSlashOfEnd(path);
  1131. };
  1132. pageSchema.statics.allPageCount = function() {
  1133. return this.count({ redirectTo: null });
  1134. };
  1135. pageSchema.statics.GRANT_PUBLIC = GRANT_PUBLIC;
  1136. pageSchema.statics.GRANT_RESTRICTED = GRANT_RESTRICTED;
  1137. pageSchema.statics.GRANT_SPECIFIED = GRANT_SPECIFIED;
  1138. pageSchema.statics.GRANT_OWNER = GRANT_OWNER;
  1139. pageSchema.statics.GRANT_USER_GROUP = GRANT_USER_GROUP;
  1140. pageSchema.statics.PAGE_GRANT_ERROR = PAGE_GRANT_ERROR;
  1141. pageSchema.statics.PageQueryBuilder = PageQueryBuilder;
  1142. return mongoose.model('Page', pageSchema);
  1143. };