page.js 41 KB

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