page.js 41 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399
  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:hideRestrictedByGroup');
  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. await savedPage.populateDataToShowRevision();
  824. if (socketClientId != null) {
  825. pageEvent.emit('create', savedPage, user, socketClientId);
  826. }
  827. return savedPage;
  828. };
  829. pageSchema.statics.updatePage = async function(pageData, body, previousBody, user, options = {}) {
  830. validateCrowi();
  831. const Revision = crowi.model('Revision');
  832. const grant = options.grant || pageData.grant; // use the previous data if absence
  833. const grantUserGroupId = options.grantUserGroupId || pageData.grantUserGroupId; // use the previous data if absence
  834. const isSyncRevisionToHackmd = options.isSyncRevisionToHackmd;
  835. const socketClientId = options.socketClientId || null;
  836. await validateAppliedScope(user, grant, grantUserGroupId);
  837. pageData.applyScope(user, grant, grantUserGroupId);
  838. // update existing page
  839. let savedPage = await pageData.save();
  840. const newRevision = await Revision.prepareRevision(pageData, body, previousBody, user);
  841. const revision = await pushRevision(savedPage, newRevision, user);
  842. savedPage = await this.findByPath(revision.path);
  843. await savedPage.populateDataToShowRevision();
  844. if (isSyncRevisionToHackmd) {
  845. savedPage = await this.syncRevisionToHackmd(savedPage);
  846. }
  847. if (socketClientId != null) {
  848. pageEvent.emit('update', savedPage, user, socketClientId);
  849. }
  850. return savedPage;
  851. };
  852. pageSchema.statics.applyScopesToDescendantsAsyncronously = async function(parentPage, user) {
  853. const builder = new PageQueryBuilder(this.find());
  854. builder.addConditionToListWithDescendants(parentPage.path);
  855. builder.addConditionToExcludeRedirect();
  856. // add grant conditions
  857. await addConditionToFilteringByViewerForList(builder, user);
  858. // get all pages that the specified user can update
  859. const pages = await builder.query.exec();
  860. for (const page of pages) {
  861. // skip parentPage
  862. if (page.id === parentPage.id) {
  863. continue;
  864. }
  865. page.applyScope(user, parentPage.grant, parentPage.grantedGroup);
  866. page.save();
  867. }
  868. };
  869. pageSchema.statics.deletePage = async function(pageData, user, options = {}) {
  870. const newPath = this.getDeletedPageName(pageData.path);
  871. const isTrashed = checkIfTrashed(pageData.path);
  872. if (isTrashed) {
  873. throw new Error('This method does NOT support deleting trashed pages.');
  874. }
  875. const socketClientId = options.socketClientId || null;
  876. if (this.isDeletableName(pageData.path)) {
  877. pageData.status = STATUS_DELETED;
  878. const updatedPageData = await this.rename(pageData, newPath, user, { socketClientId, createRedirectPage: true });
  879. return updatedPageData;
  880. }
  881. return Promise.reject(new Error('Page is not deletable.'));
  882. };
  883. const checkIfTrashed = (path) => {
  884. return (path.search(/^\/trash/) !== -1);
  885. };
  886. pageSchema.statics.deletePageRecursively = async function(targetPage, user, options = {}) {
  887. const isTrashed = checkIfTrashed(targetPage.path);
  888. if (isTrashed) {
  889. throw new Error('This method does NOT supports deleting trashed pages.');
  890. }
  891. const findOpts = { includeRedirect: true };
  892. const result = await this.findListWithDescendants(targetPage.path, user, findOpts);
  893. const pages = result.pages;
  894. let updatedPage = null;
  895. await Promise.all(pages.map((page) => {
  896. const isParent = (page.path === targetPage.path);
  897. const p = this.deletePage(page, user, options);
  898. if (isParent) {
  899. updatedPage = p;
  900. }
  901. return p;
  902. }));
  903. return updatedPage;
  904. };
  905. pageSchema.statics.revertDeletedPage = async function(page, user, options = {}) {
  906. const newPath = this.getRevertDeletedPageName(page.path);
  907. const originPage = await this.findByPath(newPath);
  908. if (originPage != null) {
  909. // 削除時、元ページの path には必ず redirectTo 付きで、ページが作成される。
  910. // そのため、そいつは削除してOK
  911. // が、redirectTo ではないページが存在している場合それは何かがおかしい。(データ補正が必要)
  912. if (originPage.redirectTo !== page.path) {
  913. throw new Error('The new page of to revert is exists and the redirect path of the page is not the deleted page.');
  914. }
  915. await this.completelyDeletePage(originPage, options);
  916. }
  917. page.status = STATUS_PUBLISHED;
  918. page.lastUpdateUser = user;
  919. debug('Revert deleted the page', page, newPath);
  920. const updatedPage = await this.rename(page, newPath, user, {});
  921. return updatedPage;
  922. };
  923. pageSchema.statics.revertDeletedPageRecursively = async function(targetPage, user, options = {}) {
  924. const findOpts = { includeRedirect: true, includeTrashed: true };
  925. const result = await this.findListWithDescendants(targetPage.path, user, findOpts);
  926. const pages = result.pages;
  927. let updatedPage = null;
  928. await Promise.all(pages.map((page) => {
  929. const isParent = (page.path === targetPage.path);
  930. const p = this.revertDeletedPage(page, user, options);
  931. if (isParent) {
  932. updatedPage = p;
  933. }
  934. return p;
  935. }));
  936. return updatedPage;
  937. };
  938. /**
  939. * This is danger.
  940. */
  941. pageSchema.statics.completelyDeletePage = async function(pageData, user, options = {}) {
  942. validateCrowi();
  943. // Delete Bookmarks, Attachments, Revisions, Pages and emit delete
  944. const Bookmark = crowi.model('Bookmark');
  945. const Attachment = crowi.model('Attachment');
  946. const Comment = crowi.model('Comment');
  947. const PageTagRelation = crowi.model('PageTagRelation');
  948. const Revision = crowi.model('Revision');
  949. const pageId = pageData._id;
  950. const socketClientId = options.socketClientId || null;
  951. debug('Completely delete', pageData.path);
  952. await Bookmark.removeBookmarksByPageId(pageId);
  953. await Attachment.removeAttachmentsByPageId(pageId);
  954. await Comment.removeCommentsByPageId(pageId);
  955. await PageTagRelation.remove({ relatedPage: 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, transferToUserGroupId) {
  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, transferToUserGroupId);
  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, transferToUserGroupId) {
  1073. const UserGroup = mongoose.model('UserGroup');
  1074. // check page existence
  1075. const isExist = await UserGroup.count({ _id: transferToUserGroupId }) > 0;
  1076. if (isExist) {
  1077. page.grantedGroup = transferToUserGroupId;
  1078. await page.save();
  1079. }
  1080. else {
  1081. throw new Error('Cannot find the group to which private pages belong to. _id: ', transferToUserGroupId);
  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. };