page.js 42 KB

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