page.js 37 KB

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