page.js 35 KB

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