2
0

page.js 41 KB

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