page.js 39 KB

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