page.js 38 KB

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