page.js 41 KB

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