page.js 41 KB

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