page.js 41 KB

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