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