page.js 41 KB

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