page.js 41 KB

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