page.js 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419
  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. {status: null},
  577. {status: STATUS_PUBLISHED},
  578. ]},
  579. {$or: [
  580. {grant: GRANT_PUBLIC},
  581. {grant: GRANT_USER_GROUP},
  582. ]}],
  583. };
  584. return new Promise(function(resolve, reject) {
  585. Page
  586. .find(conditions)
  587. .sort({createdAt: -1})
  588. .skip(offset)
  589. .limit(limit)
  590. .populate('revision')
  591. .exec()
  592. .then(function(pages) {
  593. return Page.populate(pages, {path: 'lastUpdateUser', model: 'User', select: User.USER_PUBLIC_FIELDS}).then(function(pagesData){
  594. let countFetcher;
  595. countFetcher = Page.countListByCreator(user,option,currentUser);
  596. countFetcher.then(function(count){
  597. pagesArray = [
  598. {totalCount: count}
  599. ];
  600. pagesArray.push(pagesData);
  601. resolve(pagesArray);
  602. });
  603. });
  604. });
  605. });
  606. };
  607. pageSchema.statics.countListByCreator = function(user, option, currentUser) {
  608. var Page = this;
  609. var User = crowi.model('User');
  610. var conditions = {
  611. creator: user._id,
  612. redirectTo: null,
  613. $and : [
  614. {$or: [
  615. {status: null},
  616. {status: STATUS_PUBLISHED},
  617. ]},
  618. {$or: [
  619. {grant: GRANT_PUBLIC},
  620. {grant: GRANT_USER_GROUP},
  621. ]}],
  622. };
  623. return Page.find(conditions).count();
  624. };
  625. /**
  626. * Bulk get (for internal only)
  627. */
  628. pageSchema.statics.getStreamOfFindAll = function(options) {
  629. var Page = this
  630. , options = options || {}
  631. , publicOnly = options.publicOnly || true
  632. , criteria = {redirectTo: null, }
  633. ;
  634. if (publicOnly) {
  635. criteria.grant = GRANT_PUBLIC;
  636. }
  637. return this.find(criteria)
  638. .populate([
  639. {path: 'creator', model: 'User'},
  640. {path: 'revision', model: 'Revision'},
  641. ])
  642. .sort({updatedAt: -1})
  643. .cursor();
  644. };
  645. /**
  646. * find the page that is match with `path` and its descendants
  647. */
  648. pageSchema.statics.findListWithDescendants = function(path, userData, option) {
  649. var Page = this;
  650. // ignore other pages than descendants
  651. path = Page.addSlashOfEnd(path);
  652. // add option to escape the regex strings
  653. const combinedOption = Object.assign({isRegExpEscapedFromPath: true}, option);
  654. return Page.findListByStartWith(path, userData, combinedOption);
  655. };
  656. /**
  657. * find pages that start with `path`
  658. *
  659. * see the comment of `generateQueryToListByStartWith` function
  660. */
  661. pageSchema.statics.findListByStartWith = function(path, userData, option) {
  662. var Page = this;
  663. var User = crowi.model('User');
  664. if (!option) {
  665. option = {sort: 'updatedAt', desc: -1, offset: 0, limit: 50};
  666. }
  667. var opt = {
  668. sort: option.sort || 'updatedAt',
  669. desc: option.desc || -1,
  670. offset: option.offset || 0,
  671. limit: option.limit || 50
  672. };
  673. var sortOpt = {};
  674. sortOpt[opt.sort] = opt.desc;
  675. var isPopulateRevisionBody = option.isPopulateRevisionBody || false;
  676. return new Promise(function(resolve, reject) {
  677. var q = Page.generateQueryToListByStartWith(path, userData, option)
  678. .sort(sortOpt)
  679. .skip(opt.offset)
  680. .limit(opt.limit);
  681. // retrieve revision data
  682. if (isPopulateRevisionBody) {
  683. q = q.populate('revision');
  684. }
  685. else {
  686. q = q.populate('revision', '-body'); // exclude body
  687. }
  688. q.exec()
  689. .then(function(pages) {
  690. Page.populate(pages, {path: 'lastUpdateUser', model: 'User', select: User.USER_PUBLIC_FIELDS})
  691. .then(resolve)
  692. .catch(reject);
  693. });
  694. });
  695. };
  696. /**
  697. * generate the query to find the page that is match with `path` and its descendants
  698. */
  699. pageSchema.statics.generateQueryToListWithDescendants = function(path, userData, option) {
  700. var Page = this;
  701. // ignore other pages than descendants
  702. path = Page.addSlashOfEnd(path);
  703. // add option to escape the regex strings
  704. const combinedOption = Object.assign({isRegExpEscapedFromPath: true}, option);
  705. return Page.generateQueryToListByStartWith(path, userData, combinedOption);
  706. };
  707. /**
  708. * generate the query to find pages that start with `path`
  709. *
  710. * (GROWI) If 'isRegExpEscapedFromPath' is true, `path` should have `/` at the end
  711. * -> returns '{path}/*' and '{path}' self.
  712. * (Crowi) If 'isRegExpEscapedFromPath' is false and `path` has `/` at the end
  713. * -> returns '{path}*'
  714. * (Crowi) If 'isRegExpEscapedFromPath' is false and `path` doesn't have `/` at the end
  715. * -> returns '{path}*'
  716. *
  717. * *option*
  718. * - includeDeletedPage -- if true, search deleted pages (default: false)
  719. * - isRegExpEscapedFromPath -- if true, the regex strings included in `path` is escaped (default: false)
  720. */
  721. pageSchema.statics.generateQueryToListByStartWith = function(path, userData, option) {
  722. var Page = this;
  723. var pathCondition = [];
  724. var includeDeletedPage = option.includeDeletedPage || false;
  725. var isRegExpEscapedFromPath = option.isRegExpEscapedFromPath || false;
  726. /*
  727. * 1. add condition for finding the page completely match with `path` w/o last slash
  728. */
  729. let pathSlashOmitted = path;
  730. if (path.match(/\/$/)) {
  731. pathSlashOmitted = path.substr(0, path.length -1);
  732. pathCondition.push({path: pathSlashOmitted});
  733. }
  734. /*
  735. * 2. add decendants
  736. */
  737. var pattern = (isRegExpEscapedFromPath)
  738. ? escapeStringRegexp(path) // escape
  739. : pathSlashOmitted;
  740. var queryReg = new RegExp('^' + pattern);
  741. pathCondition.push({path: queryReg});
  742. var q = Page.find({
  743. redirectTo: null,
  744. $or: [
  745. {grant: null},
  746. {grant: GRANT_PUBLIC},
  747. {grant: GRANT_RESTRICTED, grantedUsers: userData._id},
  748. {grant: GRANT_SPECIFIED, grantedUsers: userData._id},
  749. {grant: GRANT_OWNER, grantedUsers: userData._id},
  750. {grant: GRANT_USER_GROUP},
  751. ], })
  752. .and({
  753. $or: pathCondition
  754. });
  755. if (!includeDeletedPage) {
  756. q.and({
  757. $or: [
  758. {status: null},
  759. {status: STATUS_PUBLISHED},
  760. ],
  761. });
  762. }
  763. return q;
  764. };
  765. pageSchema.statics.updatePageProperty = function(page, updateData) {
  766. var Page = this;
  767. return new Promise(function(resolve, reject) {
  768. // TODO foreach して save
  769. Page.update({_id: page._id}, {$set: updateData}, function(err, data) {
  770. if (err) {
  771. return reject(err);
  772. }
  773. return resolve(data);
  774. });
  775. });
  776. };
  777. pageSchema.statics.updateGrant = function(page, grant, userData, grantUserGroupId) {
  778. var Page = this;
  779. return new Promise(function(resolve, reject) {
  780. if (grant == GRANT_USER_GROUP && grantUserGroupId == null) {
  781. reject('grant userGroupId is not specified');
  782. }
  783. page.grant = grant;
  784. if (grant == GRANT_PUBLIC || grant == GRANT_USER_GROUP) {
  785. page.grantedUsers = [];
  786. }
  787. else {
  788. page.grantedUsers = [];
  789. page.grantedUsers.push(userData._id);
  790. }
  791. page.save(function(err, data) {
  792. debug('Page.updateGrant, saved grantedUsers.', err, data);
  793. if (err) {
  794. return reject(err);
  795. }
  796. Page.updateGrantUserGroup(page, grant, grantUserGroupId, userData)
  797. .then(() => {
  798. return resolve(data);
  799. });
  800. });
  801. });
  802. };
  803. pageSchema.statics.updateGrantUserGroup = function(page, grant, grantUserGroupId, userData) {
  804. var UserGroupRelation = crowi.model('UserGroupRelation');
  805. var PageGroupRelation = crowi.model('PageGroupRelation');
  806. // グループの場合
  807. if (grant == GRANT_USER_GROUP) {
  808. debug('grant is usergroup', grantUserGroupId);
  809. return UserGroupRelation.findByGroupIdAndUser(grantUserGroupId, userData)
  810. .then((relation) => {
  811. if (relation == null) {
  812. return new Error('no relations were exist for group and user.');
  813. }
  814. return PageGroupRelation.findOrCreateRelationForPageAndGroup(page, relation.relatedGroup);
  815. })
  816. .catch((err) => {
  817. return new Error('No UserGroup is exists. userGroupId : ', grantUserGroupId);
  818. });
  819. }
  820. else {
  821. return PageGroupRelation.removeAllByPage(page);
  822. }
  823. };
  824. // Instance method でいいのでは
  825. pageSchema.statics.pushToGrantedUsers = function(page, userData) {
  826. return new Promise(function(resolve, reject) {
  827. if (!page.grantedUsers || !Array.isArray(page.grantedUsers)) {
  828. page.grantedUsers = [];
  829. }
  830. page.grantedUsers.push(userData);
  831. page.save(function(err, data) {
  832. if (err) {
  833. return reject(err);
  834. }
  835. return resolve(data);
  836. });
  837. });
  838. };
  839. pageSchema.statics.pushRevision = async function(pageData, newRevision, user) {
  840. await newRevision.save();
  841. debug('Successfully saved new revision', newRevision);
  842. pageData.revision = newRevision;
  843. pageData.lastUpdateUser = user;
  844. pageData.updatedAt = Date.now();
  845. return pageData.save();
  846. };
  847. pageSchema.statics.create = function(path, body, user, options = {}) {
  848. const Page = this
  849. , Revision = crowi.model('Revision')
  850. , format = options.format || 'markdown'
  851. , redirectTo = options.redirectTo || null
  852. , grantUserGroupId = options.grantUserGroupId || null
  853. , socketClientId = options.socketClientId || null
  854. ;
  855. let grant = options.grant || GRANT_PUBLIC;
  856. // sanitize path
  857. path = crowi.xss.process(path);
  858. // force public
  859. if (isPortalPath(path)) {
  860. grant = GRANT_PUBLIC;
  861. }
  862. let savedPage = undefined;
  863. return Page.findOne({path: path})
  864. .then(pageData => {
  865. if (pageData) {
  866. throw new Error('Cannot create new page to existed path');
  867. }
  868. const newPage = new Page();
  869. newPage.path = path;
  870. newPage.creator = user;
  871. newPage.lastUpdateUser = user;
  872. newPage.createdAt = Date.now();
  873. newPage.updatedAt = Date.now();
  874. newPage.redirectTo = redirectTo;
  875. newPage.grant = grant;
  876. newPage.status = STATUS_PUBLISHED;
  877. newPage.grantedUsers = [];
  878. newPage.grantedUsers.push(user);
  879. return newPage.save();
  880. })
  881. .then((newPage) => {
  882. savedPage = newPage;
  883. })
  884. .then(() => {
  885. const newRevision = Revision.prepareRevision(savedPage, body, user, {format: format});
  886. return Page.pushRevision(savedPage, newRevision, user);
  887. })
  888. .then(() => {
  889. return Page.updateGrantUserGroup(savedPage, grant, grantUserGroupId, user);
  890. })
  891. .then(() => {
  892. if (socketClientId != null) {
  893. pageEvent.emit('create', savedPage, user, socketClientId);
  894. }
  895. return savedPage;
  896. });
  897. };
  898. pageSchema.statics.updatePage = async function(pageData, body, user, options = {}) {
  899. const Page = this
  900. , Revision = crowi.model('Revision')
  901. , grant = options.grant || null
  902. , grantUserGroupId = options.grantUserGroupId || null
  903. , isSyncRevisionToHackmd = options.isSyncRevisionToHackmd
  904. , socketClientId = options.socketClientId || null
  905. ;
  906. // update existing page
  907. const newRevision = await Revision.prepareRevision(pageData, body, user);
  908. const revision = await Page.pushRevision(pageData, newRevision, user);
  909. let savedPage = await Page.findPageByPath(revision.path).populate('revision').populate('creator');
  910. if (grant != null) {
  911. const grantData = await Page.updateGrant(savedPage, grant, user, grantUserGroupId);
  912. debug('Page grant update:', grantData);
  913. }
  914. if (isSyncRevisionToHackmd) {
  915. savedPage = await Page.syncRevisionToHackmd(savedPage);
  916. }
  917. if (socketClientId != null) {
  918. pageEvent.emit('update', savedPage, user, socketClientId);
  919. }
  920. return savedPage;
  921. };
  922. pageSchema.statics.deletePage = async function(pageData, user, options = {}) {
  923. const Page = this
  924. , newPath = Page.getDeletedPageName(pageData.path)
  925. , isTrashed = checkIfTrashed(pageData.path)
  926. , socketClientId = options.socketClientId || null
  927. ;
  928. if (Page.isDeletableName(pageData.path)) {
  929. if (isTrashed) {
  930. return Page.completelyDeletePage(pageData, user, options);
  931. }
  932. let updatedPageData = await Page.rename(pageData, newPath, user, {createRedirectPage: true});
  933. await Page.updatePageProperty(updatedPageData, {status: STATUS_DELETED, lastUpdateUser: user});
  934. if (socketClientId != null) {
  935. pageEvent.emit('delete', updatedPageData, user, socketClientId);
  936. }
  937. return updatedPageData;
  938. }
  939. else {
  940. return Promise.reject('Page is not deletable.');
  941. }
  942. };
  943. const checkIfTrashed = (path) => {
  944. return (path.search(/^\/trash/) !== -1);
  945. };
  946. pageSchema.statics.deletePageRecursively = function(pageData, user, options) {
  947. const Page = this
  948. , path = pageData.path
  949. , isTrashed = checkIfTrashed(pageData.path)
  950. ;
  951. options = options || {};
  952. if (isTrashed) {
  953. return Page.completelyDeletePageRecursively(pageData, user, options);
  954. }
  955. return Page.generateQueryToListWithDescendants(path, user, options)
  956. .then(function(pages) {
  957. return Promise.all(pages.map(function(page) {
  958. return Page.deletePage(page, user, options);
  959. }));
  960. })
  961. .then(function(data) {
  962. return pageData;
  963. });
  964. };
  965. pageSchema.statics.revertDeletedPage = function(pageData, user, options) {
  966. const Page = this
  967. , newPath = Page.getRevertDeletedPageName(pageData.path)
  968. ;
  969. // 削除時、元ページの path には必ず redirectTo 付きで、ページが作成される。
  970. // そのため、そいつは削除してOK
  971. // が、redirectTo ではないページが存在している場合それは何かがおかしい。(データ補正が必要)
  972. return new Promise(function(resolve, reject) {
  973. Page.findPageByPath(newPath)
  974. .then(function(originPageData) {
  975. if (originPageData.redirectTo !== pageData.path) {
  976. throw new Error('The new page of to revert is exists and the redirect path of the page is not the deleted page.');
  977. }
  978. return Page.completelyDeletePage(originPageData, options);
  979. }).then(function(done) {
  980. return Page.updatePageProperty(pageData, {status: STATUS_PUBLISHED, lastUpdateUser: user});
  981. }).then(function(done) {
  982. pageData.status = STATUS_PUBLISHED;
  983. debug('Revert deleted the page, and rename again it', pageData, newPath);
  984. return Page.rename(pageData, newPath, user, {});
  985. }).then(function(done) {
  986. pageData.path = newPath;
  987. resolve(pageData);
  988. }).catch(reject);
  989. });
  990. };
  991. pageSchema.statics.revertDeletedPageRecursively = function(pageData, user, options = {}) {
  992. const Page = this
  993. , path = pageData.path
  994. ;
  995. options = Object.assign({ includeDeletedPage: true }, options);
  996. return new Promise(function(resolve, reject) {
  997. Page
  998. .generateQueryToListWithDescendants(path, user, options)
  999. .exec()
  1000. .then(function(pages) {
  1001. Promise.all(pages.map(function(page) {
  1002. return Page.revertDeletedPage(page, user, options);
  1003. }))
  1004. .then(function(data) {
  1005. return resolve(data[0]);
  1006. });
  1007. });
  1008. });
  1009. };
  1010. /**
  1011. * This is danger.
  1012. */
  1013. pageSchema.statics.completelyDeletePage = function(pageData, user, options = {}) {
  1014. // Delete Bookmarks, Attachments, Revisions, Pages and emit delete
  1015. const Bookmark = crowi.model('Bookmark')
  1016. , Attachment = crowi.model('Attachment')
  1017. , Comment = crowi.model('Comment')
  1018. , Revision = crowi.model('Revision')
  1019. , PageGroupRelation = crowi.model('PageGroupRelation')
  1020. , Page = this
  1021. , pageId = pageData._id
  1022. , socketClientId = options.socketClientId || null
  1023. ;
  1024. debug('Completely delete', pageData.path);
  1025. return new Promise(function(resolve, reject) {
  1026. Bookmark.removeBookmarksByPageId(pageId)
  1027. .then(function(done) {
  1028. }).then(function(done) {
  1029. return Attachment.removeAttachmentsByPageId(pageId);
  1030. }).then(function(done) {
  1031. return Comment.removeCommentsByPageId(pageId);
  1032. }).then(function(done) {
  1033. return Revision.removeRevisionsByPath(pageData.path);
  1034. }).then(function(done) {
  1035. return Page.removePageById(pageId);
  1036. }).then(function(done) {
  1037. return Page.removeRedirectOriginPageByPath(pageData.path);
  1038. }).then(function(done) {
  1039. return PageGroupRelation.removeAllByPage(pageData);
  1040. }).then(function(done) {
  1041. if (socketClientId != null) {
  1042. pageEvent.emit('delete', pageData, user, socketClientId); // update as renamed page
  1043. }
  1044. resolve(pageData);
  1045. }).catch(reject);
  1046. });
  1047. };
  1048. pageSchema.statics.completelyDeletePageRecursively = function(pageData, user, options = {}) {
  1049. // Delete Bookmarks, Attachments, Revisions, Pages and emit delete
  1050. const Page = this
  1051. , path = pageData.path
  1052. ;
  1053. options = Object.assign({ includeDeletedPage: true }, options);
  1054. return new Promise(function(resolve, reject) {
  1055. Page
  1056. .generateQueryToListWithDescendants(path, user, options)
  1057. .then(function(pages) {
  1058. Promise.all(pages.map(function(page) {
  1059. return Page.completelyDeletePage(page, user, options);
  1060. }))
  1061. .then(function(data) {
  1062. return resolve(data[0]);
  1063. });
  1064. });
  1065. });
  1066. };
  1067. pageSchema.statics.removePageById = function(pageId) {
  1068. var Page = this;
  1069. return new Promise(function(resolve, reject) {
  1070. Page.remove({_id: pageId}, function(err, done) {
  1071. debug('Remove phisiaclly, the page', pageId, err, done);
  1072. if (err) {
  1073. return reject(err);
  1074. }
  1075. resolve(done);
  1076. });
  1077. });
  1078. };
  1079. pageSchema.statics.removePageByPath = function(pagePath) {
  1080. var Page = this;
  1081. return Page.findPageByPath(pagePath)
  1082. .then(function(pageData) {
  1083. return Page.removePageById(pageData.id);
  1084. });
  1085. };
  1086. /**
  1087. * remove the page that is redirecting to specified `pagePath` recursively
  1088. * ex: when
  1089. * '/page1' redirects to '/page2' and
  1090. * '/page2' redirects to '/page3'
  1091. * and given '/page3',
  1092. * '/page1' and '/page2' will be removed
  1093. *
  1094. * @param {string} pagePath
  1095. */
  1096. pageSchema.statics.removeRedirectOriginPageByPath = function(pagePath) {
  1097. var Page = this;
  1098. return Page.findPageByRedirectTo(pagePath)
  1099. .then((redirectOriginPageData) => {
  1100. // remove
  1101. return Page.removePageById(redirectOriginPageData.id)
  1102. // remove recursive
  1103. .then(() => {
  1104. return Page.removeRedirectOriginPageByPath(redirectOriginPageData.path);
  1105. });
  1106. })
  1107. .catch((err) => {
  1108. // do nothing if origin page doesn't exist
  1109. return Promise.resolve();
  1110. });
  1111. };
  1112. pageSchema.statics.rename = async function(pageData, newPagePath, user, options) {
  1113. const Page = this
  1114. , Revision = crowi.model('Revision')
  1115. , path = pageData.path
  1116. , createRedirectPage = options.createRedirectPage || 0
  1117. , socketClientId = options.socketClientId || null
  1118. ;
  1119. // sanitize path
  1120. newPagePath = crowi.xss.process(newPagePath);
  1121. await Page.updatePageProperty(pageData, {updatedAt: Date.now(), path: newPagePath, lastUpdateUser: user});
  1122. // reivisions の path を変更
  1123. await Revision.updateRevisionListByPath(path, {path: newPagePath}, {});
  1124. if (createRedirectPage) {
  1125. const body = 'redirect ' + newPagePath;
  1126. await Page.create(path, body, user, {redirectTo: newPagePath});
  1127. }
  1128. let updatedPageData = await Page.findOne({path: newPagePath});
  1129. pageEvent.emit('delete', pageData, user, socketClientId);
  1130. pageEvent.emit('create', updatedPageData, user, socketClientId);
  1131. return updatedPageData;
  1132. };
  1133. pageSchema.statics.renameRecursively = function(pageData, newPagePathPrefix, user, options) {
  1134. const Page = this
  1135. , path = pageData.path
  1136. , pathRegExp = new RegExp('^' + escapeStringRegexp(path), 'i');
  1137. // sanitize path
  1138. newPagePathPrefix = crowi.xss.process(newPagePathPrefix);
  1139. return Page.generateQueryToListWithDescendants(path, user, options)
  1140. .then(function(pages) {
  1141. return Promise.all(pages.map(function(page) {
  1142. const newPagePath = page.path.replace(pathRegExp, newPagePathPrefix);
  1143. return Page.rename(page, newPagePath, user, options);
  1144. }));
  1145. })
  1146. .then(function() {
  1147. pageData.path = newPagePathPrefix;
  1148. return pageData;
  1149. });
  1150. };
  1151. /**
  1152. * associate GROWI page and HackMD page
  1153. * @param {Page} pageData
  1154. * @param {string} pageIdOnHackmd
  1155. */
  1156. pageSchema.statics.registerHackmdPage = function(pageData, pageIdOnHackmd) {
  1157. if (pageData.pageIdOnHackmd != null) {
  1158. throw new Error(`'pageIdOnHackmd' of the page '${pageData.path}' is not empty`);
  1159. }
  1160. pageData.pageIdOnHackmd = pageIdOnHackmd;
  1161. return this.syncRevisionToHackmd(pageData);
  1162. };
  1163. /**
  1164. * update revisionHackmdSynced
  1165. * @param {Page} pageData
  1166. * @param {bool} isSave whether save or not
  1167. */
  1168. pageSchema.statics.syncRevisionToHackmd = function(pageData, isSave = true) {
  1169. pageData.revisionHackmdSynced = pageData.revision;
  1170. pageData.hasDraftOnHackmd = false;
  1171. let returnData = pageData;
  1172. if (isSave) {
  1173. returnData = pageData.save();
  1174. }
  1175. return returnData;
  1176. };
  1177. /**
  1178. * update hasDraftOnHackmd
  1179. * !! This will be invoked many time from many people !!
  1180. *
  1181. * @param {Page} pageData
  1182. * @param {Boolean} newValue
  1183. */
  1184. pageSchema.statics.updateHasDraftOnHackmd = async function(pageData, newValue) {
  1185. if (pageData.hasDraftOnHackmd === newValue) {
  1186. // do nothing when hasDraftOnHackmd equals to newValue
  1187. return;
  1188. }
  1189. pageData.hasDraftOnHackmd = newValue;
  1190. return pageData.save();
  1191. };
  1192. pageSchema.statics.getHistories = function() {
  1193. // TODO
  1194. return;
  1195. };
  1196. /**
  1197. * return path that added slash to the end for specified path
  1198. */
  1199. pageSchema.statics.addSlashOfEnd = function(path) {
  1200. let returnPath = path;
  1201. if (!path.match(/\/$/)) {
  1202. returnPath += '/';
  1203. }
  1204. return returnPath;
  1205. };
  1206. pageSchema.statics.GRANT_PUBLIC = GRANT_PUBLIC;
  1207. pageSchema.statics.GRANT_RESTRICTED = GRANT_RESTRICTED;
  1208. pageSchema.statics.GRANT_SPECIFIED = GRANT_SPECIFIED;
  1209. pageSchema.statics.GRANT_OWNER = GRANT_OWNER;
  1210. pageSchema.statics.PAGE_GRANT_ERROR = PAGE_GRANT_ERROR;
  1211. return mongoose.model('Page', pageSchema);
  1212. };