page.js 38 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280
  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. Page.isExistsGrantedGroupFor(pageData, userData)
  387. .then(function (checkResult) {
  388. debug('isExistsGrantedGroupFor checkResult is ', checkResult);
  389. if (!checkResult) {
  390. return reject(new Error('Page is not granted for the user')); //PAGE_GRANT_ERROR, null);
  391. } else {
  392. return resolve(pageData);
  393. }
  394. })
  395. .catch(function(err) {
  396. return reject(err);
  397. });
  398. }
  399. return resolve(pageData);
  400. }).catch(function(err) {
  401. return reject(err);
  402. });
  403. });
  404. };
  405. // find page and check if granted user
  406. pageSchema.statics.findPage = function(path, userData, revisionId, ignoreNotFound) {
  407. var self = this;
  408. return new Promise(function(resolve, reject) {
  409. self.findOne({path: path}, function(err, pageData) {
  410. if (err) {
  411. return reject(err);
  412. }
  413. if (pageData === null) {
  414. if (ignoreNotFound) {
  415. return resolve(null);
  416. }
  417. var pageNotFoundError = new Error('Page Not Found')
  418. pageNotFoundError.name = 'Crowi:Page:NotFound';
  419. return reject(pageNotFoundError);
  420. }
  421. if (!pageData.isGrantedFor(userData)) {
  422. self.isExistsGrantedGroupFor(pageData, userData)
  423. .then(function (checkResult) {
  424. debug('isExistsGrantedGroupFor checkResult is ', checkResult);
  425. if (!checkResult) {
  426. return reject(new Error('Page is not granted for the user')); //PAGE_GRANT_ERROR, null);
  427. } else {
  428. // return resolve(pageData);
  429. self.populatePageData(pageData, revisionId || null).then(resolve).catch(reject);
  430. }
  431. })
  432. .catch(function (err) {
  433. return reject(err);
  434. });
  435. }
  436. else {
  437. self.populatePageData(pageData, revisionId || null).then(resolve).catch(reject);
  438. }
  439. });
  440. });
  441. };
  442. // find page by path
  443. pageSchema.statics.findPageByPath = function(path) {
  444. var Page = this;
  445. return new Promise(function(resolve, reject) {
  446. Page.findOne({path: path}, function(err, pageData) {
  447. if (err || pageData === null) {
  448. return reject(err);
  449. }
  450. return resolve(pageData);
  451. });
  452. });
  453. };
  454. pageSchema.statics.findListByPageIds = function(ids, options) {
  455. var Page = this;
  456. var User = crowi.model('User');
  457. var options = options || {}
  458. , limit = options.limit || 50
  459. , offset = options.skip || 0
  460. ;
  461. return new Promise(function(resolve, reject) {
  462. Page
  463. .find({ _id: { $in: ids }, grant: GRANT_PUBLIC })
  464. //.sort({createdAt: -1}) // TODO optionize
  465. .skip(offset)
  466. .limit(limit)
  467. .populate([
  468. {path: 'creator', model: 'User', select: User.USER_PUBLIC_FIELDS},
  469. {path: 'revision', model: 'Revision'},
  470. ])
  471. .exec(function(err, pages) {
  472. if (err) {
  473. return reject(err);
  474. }
  475. Page.populate(pages, {path: 'revision.author', model: 'User', select: User.USER_PUBLIC_FIELDS}, function(err, data) {
  476. if (err) {
  477. return reject(err);
  478. }
  479. return resolve(data);
  480. });
  481. });
  482. });
  483. };
  484. pageSchema.statics.findPageByRedirectTo = function(path) {
  485. var Page = this;
  486. return new Promise(function(resolve, reject) {
  487. Page.findOne({redirectTo: path}, function(err, pageData) {
  488. if (err || pageData === null) {
  489. return reject(err);
  490. }
  491. return resolve(pageData);
  492. });
  493. });
  494. };
  495. pageSchema.statics.findListByCreator = function(user, option, currentUser) {
  496. var Page = this;
  497. var User = crowi.model('User');
  498. var limit = option.limit || 50;
  499. var offset = option.offset || 0;
  500. var conditions = {
  501. creator: user._id,
  502. redirectTo: null,
  503. $or: [
  504. {status: null},
  505. {status: STATUS_PUBLISHED},
  506. ],
  507. };
  508. if (!user.equals(currentUser._id)) {
  509. conditions.grant = GRANT_PUBLIC;
  510. }
  511. return new Promise(function(resolve, reject) {
  512. Page
  513. .find(conditions)
  514. .sort({createdAt: -1})
  515. .skip(offset)
  516. .limit(limit)
  517. .populate('revision')
  518. .exec()
  519. .then(function(pages) {
  520. return Page.populate(pages, {path: 'revision.author', model: 'User', select: User.USER_PUBLIC_FIELDS}).then(resolve);
  521. });
  522. });
  523. };
  524. /**
  525. * Bulk get (for internal only)
  526. */
  527. pageSchema.statics.getStreamOfFindAll = function(options) {
  528. var Page = this
  529. , options = options || {}
  530. , publicOnly = options.publicOnly || true
  531. , criteria = {redirectTo: null,}
  532. ;
  533. if (publicOnly) {
  534. criteria.grant = GRANT_PUBLIC;
  535. }
  536. return this.find(criteria)
  537. .populate([
  538. {path: 'creator', model: 'User'},
  539. {path: 'revision', model: 'Revision'},
  540. ])
  541. .sort({updatedAt: -1})
  542. .cursor();
  543. };
  544. /**
  545. * find the page that is match with `path` and its descendants
  546. */
  547. pageSchema.statics.findListWithDescendants = function(path, userData, option) {
  548. var Page = this;
  549. // ignore other pages than descendants
  550. path = Page.addSlashOfEnd(path);
  551. // add option to escape the regex strings
  552. const combinedOption = Object.assign({isRegExpEscapedFromPath: true}, option);
  553. return Page.findListByStartWith(path, userData, combinedOption);
  554. };
  555. /**
  556. * find pages that start with `path`
  557. *
  558. * see the comment of `generateQueryToListByStartWith` function
  559. */
  560. pageSchema.statics.findListByStartWith = function(path, userData, option) {
  561. var Page = this;
  562. var User = crowi.model('User');
  563. if (!option) {
  564. option = {sort: 'updatedAt', desc: -1, offset: 0, limit: 50};
  565. }
  566. var opt = {
  567. sort: option.sort || 'updatedAt',
  568. desc: option.desc || -1,
  569. offset: option.offset || 0,
  570. limit: option.limit || 50
  571. };
  572. var sortOpt = {};
  573. sortOpt[opt.sort] = opt.desc;
  574. var isPopulateRevisionBody = option.isPopulateRevisionBody || false;
  575. return new Promise(function(resolve, reject) {
  576. var q = Page.generateQueryToListByStartWith(path, userData, option)
  577. .sort(sortOpt)
  578. .skip(opt.offset)
  579. .limit(opt.limit);
  580. // retrieve revision data
  581. if (isPopulateRevisionBody) {
  582. q = q.populate('revision');
  583. }
  584. else {
  585. q = q.populate('revision', '-body'); // exclude body
  586. }
  587. q.exec()
  588. .then(function(pages) {
  589. Page.populate(pages, {path: 'revision.author', model: 'User', select: User.USER_PUBLIC_FIELDS})
  590. .then(resolve)
  591. .catch(reject);
  592. })
  593. });
  594. };
  595. /**
  596. * generate the query to find the page that is match with `path` and its descendants
  597. */
  598. pageSchema.statics.generateQueryToListWithDescendants = function(path, userData, option) {
  599. var Page = this;
  600. // ignore other pages than descendants
  601. path = Page.addSlashOfEnd(path);
  602. // add option to escape the regex strings
  603. const combinedOption = Object.assign({isRegExpEscapedFromPath: true}, option);
  604. return Page.generateQueryToListByStartWith(path, userData, combinedOption);
  605. };
  606. /**
  607. * generate the query to find pages that start with `path`
  608. *
  609. * If `path` has `/` at the end, returns '{path}/*' and '{path}' self.
  610. * If `path` doesn't have `/` at the end, returns '{path}*'
  611. *
  612. * *option*
  613. * - includeDeletedPage -- if true, search deleted pages (default: false)
  614. * - isRegExpEscapedFromPath -- if true, the regex strings included in `path` is escaped (default: false)
  615. */
  616. pageSchema.statics.generateQueryToListByStartWith = function(path, userData, option) {
  617. var Page = this;
  618. var pathCondition = [];
  619. var includeDeletedPage = option.includeDeletedPage || false;
  620. var isRegExpEscapedFromPath = option.isRegExpEscapedFromPath || false;
  621. // create forward match pattern
  622. var pattern = (isRegExpEscapedFromPath)
  623. ? `^${escapeStringRegexp(path)}` // escape
  624. : `^${path}`;
  625. var queryReg = new RegExp(pattern);
  626. pathCondition.push({path: queryReg});
  627. // add condition for finding the page completely match with `path`
  628. if (path.match(/\/$/)) {
  629. debug('Page list by ending with /, so find also upper level page');
  630. pathCondition.push({path: path.substr(0, path.length -1)});
  631. }
  632. var q = Page.find({
  633. redirectTo: null,
  634. $or: [
  635. {grant: null},
  636. {grant: GRANT_PUBLIC},
  637. {grant: GRANT_RESTRICTED, grantedUsers: userData._id},
  638. {grant: GRANT_SPECIFIED, grantedUsers: userData._id},
  639. {grant: GRANT_OWNER, grantedUsers: userData._id},
  640. ],})
  641. .and({
  642. $or: pathCondition
  643. });
  644. if (!includeDeletedPage) {
  645. q.and({
  646. $or: [
  647. {status: null},
  648. {status: STATUS_PUBLISHED},
  649. ],
  650. });
  651. }
  652. return q;
  653. }
  654. pageSchema.statics.updatePageProperty = function(page, updateData) {
  655. var Page = this;
  656. return new Promise(function(resolve, reject) {
  657. // TODO foreach して save
  658. Page.update({_id: page._id}, {$set: updateData}, function(err, data) {
  659. if (err) {
  660. return reject(err);
  661. }
  662. return resolve(data);
  663. });
  664. });
  665. };
  666. pageSchema.statics.updateGrant = function (page, grant, userData, grantUserGroupId) {
  667. var Page = this;
  668. var PageGroupRelation = crowi.model('PageGroupRelation');
  669. var UserGroupRelation = crowi.model('UserGroupRelation');
  670. var provGrant = page.grant;
  671. var grantUserGroup = null;
  672. if (grant == GRANT_USER_GROUP && grantUserGroupId == null) {
  673. grant = GRANT_PUBLIC;
  674. }
  675. return new Promise(function(resolve, reject) {
  676. page.grant = grant;
  677. if (grant == GRANT_PUBLIC || grant == GRANT_USER_GROUP) {
  678. page.grantedUsers = [];
  679. } else {
  680. page.grantedUsers = [];
  681. page.grantedUsers.push(userData._id);
  682. }
  683. page.save(function(err, data) {
  684. debug('Page.updateGrant, saved grantedUsers.', err, data);
  685. if (err) {
  686. return reject(err);
  687. }
  688. // グループの場合
  689. if (grant == GRANT_USER_GROUP) {
  690. debug('grant is usergroup', grantUserGroupId);
  691. UserGroupRelation.findByGroupIdAndUser(grantUserGroupId, userData)
  692. .then(function(relation) {
  693. debug('userGroupRelation is found : ', relation)
  694. if (relation != null) {
  695. grantUserGroup = relation.relatedGroup;
  696. return PageGroupRelation.isExistsRelationForPageAndGroup(page, grantUserGroup);
  697. }
  698. else { return reject(new Error('No UserGroup is exists. userGroupId : ', grantUserGroupId)); }
  699. })
  700. .then(function(isAlreadyExists) {
  701. debug('pageGroupRelation is exists ', isAlreadyExists);
  702. if (!isAlreadyExists) {
  703. debug('create new Page and Group relations', grantUserGroup);
  704. PageGroupRelation.createRelation(grantUserGroup, page)
  705. .then(function(relationData) {
  706. return Promise.resolve();
  707. });
  708. }
  709. });
  710. }
  711. else {
  712. PageGroupRelation.removeAllByPage(page);
  713. }
  714. return resolve(data);
  715. });
  716. });
  717. };
  718. // Instance method でいいのでは
  719. pageSchema.statics.pushToGrantedUsers = function(page, userData) {
  720. return new Promise(function(resolve, reject) {
  721. if (!page.grantedUsers || !Array.isArray(page.grantedUsers)) {
  722. page.grantedUsers = [];
  723. }
  724. page.grantedUsers.push(userData);
  725. page.save(function(err, data) {
  726. if (err) {
  727. return reject(err);
  728. }
  729. return resolve(data);
  730. });
  731. });
  732. };
  733. pageSchema.statics.pushRevision = function(pageData, newRevision, user) {
  734. var isCreate = false;
  735. if (pageData.revision === undefined) {
  736. debug('pushRevision on Create');
  737. isCreate = true;
  738. }
  739. return new Promise(function(resolve, reject) {
  740. newRevision.save(function(err, newRevision) {
  741. if (err) {
  742. debug('Error on saving revision', err);
  743. return reject(err);
  744. }
  745. debug('Successfully saved new revision', newRevision);
  746. pageData.revision = newRevision;
  747. pageData.lastUpdateUser = user;
  748. pageData.updatedAt = Date.now();
  749. pageData.save(function(err, data) {
  750. if (err) {
  751. // todo: remove new revision?
  752. debug('Error on save page data (after push revision)', err);
  753. return reject(err);
  754. }
  755. resolve(data);
  756. if (!isCreate) {
  757. debug('pushRevision on Update');
  758. }
  759. });
  760. });
  761. });
  762. };
  763. pageSchema.statics.create = function(path, body, user, options) {
  764. var Page = this
  765. , Revision = crowi.model('Revision')
  766. , format = options.format || 'markdown'
  767. , grant = options.grant || GRANT_PUBLIC
  768. , redirectTo = options.redirectTo || null
  769. , grantUserGroupId = options.grantUserGroupId || null;
  770. // force public
  771. if (isPortalPath(path)) {
  772. grant = GRANT_PUBLIC;
  773. }
  774. return new Promise(function(resolve, reject) {
  775. Page.findOne({path: path}, function(err, pageData) {
  776. if (pageData) {
  777. return reject(new Error('Cannot create new page to existed path'));
  778. }
  779. var newPage = new Page();
  780. newPage.path = path;
  781. newPage.creator = user;
  782. newPage.lastUpdateUser = user;
  783. newPage.createdAt = Date.now();
  784. newPage.updatedAt = Date.now();
  785. newPage.redirectTo = redirectTo;
  786. newPage.grant = grant;
  787. newPage.status = STATUS_PUBLISHED;
  788. newPage.grantedUsers = [];
  789. newPage.grantedUsers.push(user);
  790. newPage.save(function (err, newPage) {
  791. if (err) {
  792. return reject(err);
  793. }
  794. if (newPage.grant == Page.GRANT_USER_GROUP && grantUserGroupId != null) {
  795. PageGroupRelation.createRelation(grantUserGroupId, newPage, function (err, relationData) {
  796. if (err) {
  797. return reject(err);
  798. }
  799. });
  800. }
  801. var newRevision = Revision.prepareRevision(newPage, body, user, {format: format});
  802. Page.pushRevision(newPage, newRevision, user).then(function(data) {
  803. resolve(data);
  804. pageEvent.emit('create', data, user);
  805. }).catch(function(err) {
  806. debug('Push Revision Error on create page', err);
  807. return reject(err);
  808. });
  809. });
  810. });
  811. });
  812. };
  813. pageSchema.statics.updatePage = function(pageData, body, user, options) {
  814. var Page = this
  815. , Revision = crowi.model('Revision')
  816. , grant = options.grant || null
  817. , grantUserGroupId = options.grantUserGroupId || null
  818. ;
  819. // update existing page
  820. var newRevision = Revision.prepareRevision(pageData, body, user);
  821. return new Promise(function(resolve, reject) {
  822. Page.pushRevision(pageData, newRevision, user)
  823. .then(function(revision) {
  824. if (grant != pageData.grant) {
  825. return Page.updateGrant(pageData, grant, user, grantUserGroupId).then(function(data) {
  826. debug('Page grant update:', data);
  827. resolve(data);
  828. pageEvent.emit('update', data, user);
  829. });
  830. } else {
  831. resolve(pageData);
  832. pageEvent.emit('update', pageData, user);
  833. }
  834. }).catch(function(err) {
  835. debug('Error on update', err);
  836. debug('Error on update', err.stack);
  837. });
  838. });
  839. };
  840. pageSchema.statics.deletePage = function(pageData, user, options) {
  841. var Page = this
  842. , newPath = Page.getDeletedPageName(pageData.path)
  843. ;
  844. if (Page.isDeletableName(pageData.path)) {
  845. return new Promise(function(resolve, reject) {
  846. Page.updatePageProperty(pageData, {status: STATUS_DELETED, lastUpdateUser: user})
  847. .then(function(data) {
  848. pageData.status = STATUS_DELETED;
  849. // ページ名が /trash/ 以下に存在する場合、おかしなことになる
  850. // が、 /trash 以下にページが有るのは、個別に作っていたケースのみ。
  851. // 一応しばらく前から uncreatable pages になっているのでこれでいいことにする
  852. debug('Deleted the page, and rename it', pageData.path, newPath);
  853. return Page.rename(pageData, newPath, user, {createRedirectPage: true})
  854. }).then(function(pageData) {
  855. resolve(pageData);
  856. }).catch(reject);
  857. });
  858. } else {
  859. return Promise.reject('Page is not deletable.');
  860. }
  861. };
  862. pageSchema.statics.deletePageRecursively = function (pageData, user, options) {
  863. var Page = this
  864. , path = pageData.path
  865. , options = options || {}
  866. ;
  867. return new Promise(function (resolve, reject) {
  868. Page
  869. .generateQueryToListWithDescendants(path, user, options)
  870. .then(function (pages) {
  871. Promise.all(pages.map(function (page) {
  872. return Page.deletePage(page, user, options);
  873. }))
  874. .then(function (data) {
  875. return resolve(pageData);
  876. });
  877. });
  878. });
  879. };
  880. pageSchema.statics.revertDeletedPage = function(pageData, user, options) {
  881. var Page = this
  882. , newPath = Page.getRevertDeletedPageName(pageData.path)
  883. ;
  884. // 削除時、元ページの path には必ず redirectTo 付きで、ページが作成される。
  885. // そのため、そいつは削除してOK
  886. // が、redirectTo ではないページが存在している場合それは何かがおかしい。(データ補正が必要)
  887. return new Promise(function(resolve, reject) {
  888. Page.findPageByPath(newPath)
  889. .then(function(originPageData) {
  890. if (originPageData.redirectTo !== pageData.path) {
  891. throw new Error('The new page of to revert is exists and the redirect path of the page is not the deleted page.');
  892. }
  893. return Page.completelyDeletePage(originPageData);
  894. }).then(function(done) {
  895. return Page.updatePageProperty(pageData, {status: STATUS_PUBLISHED, lastUpdateUser: user})
  896. }).then(function(done) {
  897. pageData.status = STATUS_PUBLISHED;
  898. debug('Revert deleted the page, and rename again it', pageData, newPath);
  899. return Page.rename(pageData, newPath, user, {})
  900. }).then(function(done) {
  901. pageData.path = newPath;
  902. resolve(pageData);
  903. }).catch(reject);
  904. });
  905. };
  906. pageSchema.statics.revertDeletedPageRecursively = function (pageData, user, options) {
  907. var Page = this
  908. , path = pageData.path
  909. , options = options || { includeDeletedPage: true}
  910. ;
  911. return new Promise(function (resolve, reject) {
  912. Page
  913. .generateQueryToListWithDescendants(path, user, options)
  914. .then(function (pages) {
  915. Promise.all(pages.map(function (page) {
  916. return Page.revertDeletedPage(page, user, options);
  917. }))
  918. .then(function (data) {
  919. return resolve(data[0]);
  920. });
  921. });
  922. });
  923. };
  924. /**
  925. * This is danger.
  926. */
  927. pageSchema.statics.completelyDeletePage = function(pageData, user, options) {
  928. // Delete Bookmarks, Attachments, Revisions, Pages and emit delete
  929. var Bookmark = crowi.model('Bookmark')
  930. , Attachment = crowi.model('Attachment')
  931. , Comment = crowi.model('Comment')
  932. , Revision = crowi.model('Revision')
  933. , Page = this
  934. , pageId = pageData._id
  935. ;
  936. debug('Completely delete', pageData.path);
  937. return new Promise(function(resolve, reject) {
  938. Bookmark.removeBookmarksByPageId(pageId)
  939. .then(function(done) {
  940. }).then(function(done) {
  941. return Attachment.removeAttachmentsByPageId(pageId);
  942. }).then(function(done) {
  943. return Comment.removeCommentsByPageId(pageId);
  944. }).then(function(done) {
  945. return Revision.removeRevisionsByPath(pageData.path);
  946. }).then(function(done) {
  947. return Page.removePageById(pageId);
  948. }).then(function(done) {
  949. return Page.removeRedirectOriginPageByPath(pageData.path);
  950. }).then(function(done) {
  951. pageEvent.emit('delete', pageData, user); // update as renamed page
  952. resolve(pageData);
  953. }).catch(reject);
  954. });
  955. };
  956. pageSchema.statics.completelyDeletePageRecursively = function (pageData, user, options) {
  957. // Delete Bookmarks, Attachments, Revisions, Pages and emit delete
  958. var Page = this
  959. , path = pageData.path
  960. , options = options || { includeDeletedPage: true }
  961. ;
  962. return new Promise(function (resolve, reject) {
  963. Page
  964. .generateQueryToListWithDescendants(path, user, options)
  965. .then(function (pages) {
  966. Promise.all(pages.map(function (page) {
  967. return Page.completelyDeletePage(page, user, options);
  968. }))
  969. .then(function (data) {
  970. return resolve(data[0]);
  971. });
  972. });
  973. });
  974. };
  975. pageSchema.statics.removePageById = function(pageId) {
  976. var Page = this;
  977. return new Promise(function(resolve, reject) {
  978. Page.remove({_id: pageId}, function(err, done) {
  979. debug('Remove phisiaclly, the page', pageId, err, done);
  980. if (err) {
  981. return reject(err);
  982. }
  983. resolve(done);
  984. });
  985. });
  986. };
  987. pageSchema.statics.removePageByPath = function(pagePath) {
  988. var Page = this;
  989. return Page.findPageByPath(pagePath)
  990. .then(function(pageData) {
  991. return Page.removePageById(pageData.id);
  992. });
  993. };
  994. /**
  995. * remove the page that is redirecting to specified `pagePath` recursively
  996. * ex: when
  997. * '/page1' redirects to '/page2' and
  998. * '/page2' redirects to '/page3'
  999. * and given '/page3',
  1000. * '/page1' and '/page2' will be removed
  1001. *
  1002. * @param {string} pagePath
  1003. */
  1004. pageSchema.statics.removeRedirectOriginPageByPath = function(pagePath) {
  1005. var Page = this;
  1006. return Page.findPageByRedirectTo(pagePath)
  1007. .then((redirectOriginPageData) => {
  1008. // remove
  1009. return Page.removePageById(redirectOriginPageData.id)
  1010. // remove recursive
  1011. .then(() => {
  1012. return Page.removeRedirectOriginPageByPath(redirectOriginPageData.path)
  1013. });
  1014. })
  1015. .catch((err) => {
  1016. // do nothing if origin page doesn't exist
  1017. return Promise.resolve();
  1018. })
  1019. };
  1020. pageSchema.statics.rename = function(pageData, newPagePath, user, options) {
  1021. var Page = this
  1022. , Revision = crowi.model('Revision')
  1023. , path = pageData.path
  1024. , createRedirectPage = options.createRedirectPage || 0
  1025. , moveUnderTrees = options.moveUnderTrees || 0;
  1026. return new Promise(function(resolve, reject) {
  1027. // pageData の path を変更
  1028. Page.updatePageProperty(pageData, {updatedAt: Date.now(), path: newPagePath, lastUpdateUser: user})
  1029. .then(function(data) {
  1030. // reivisions の path を変更
  1031. return Revision.updateRevisionListByPath(path, {path: newPagePath}, {})
  1032. }).then(function(data) {
  1033. pageData.path = newPagePath;
  1034. if (createRedirectPage) {
  1035. var body = 'redirect ' + newPagePath;
  1036. Page.create(path, body, user, {redirectTo: newPagePath}).then(resolve).catch(reject);
  1037. } else {
  1038. resolve(data);
  1039. }
  1040. pageEvent.emit('update', pageData, user); // update as renamed page
  1041. });
  1042. });
  1043. };
  1044. pageSchema.statics.renameRecursively = function(pageData, newPagePathPrefix, user, options) {
  1045. var Page = this
  1046. , path = pageData.path
  1047. , pathRegExp = new RegExp('^' + escapeStringRegexp(path), 'i');
  1048. return new Promise(function(resolve, reject) {
  1049. Page
  1050. .generateQueryToListWithDescendants(path, user, options)
  1051. .then(function(pages) {
  1052. Promise.all(pages.map(function(page) {
  1053. newPagePath = page.path.replace(pathRegExp, newPagePathPrefix);
  1054. return Page.rename(page, newPagePath, user, options);
  1055. }))
  1056. .then(function() {
  1057. pageData.path = newPagePathPrefix;
  1058. return resolve();
  1059. });
  1060. });
  1061. });
  1062. };
  1063. pageSchema.statics.getHistories = function() {
  1064. // TODO
  1065. return;
  1066. };
  1067. // 指定ページに紐づくユーザグループに、対象のユーザが含まれるかを確認
  1068. pageSchema.statics.isExistsGrantedGroupFor = function(pageData, userData) {
  1069. var PageGroupRelation = crowi.model('PageGroupRelation');
  1070. var UserGroupRelation = crowi.model('UserGroupRelation');
  1071. debug('isExistsGrantedGroupFor is called.');
  1072. return new Promise(function (resolve, reject) {
  1073. PageGroupRelation.findByPage(pageData)
  1074. .then(function (pageRelations) {
  1075. debug('PageGroupRelation.findByPage result is ', pageRelations);
  1076. if (pageRelations == null) {
  1077. debug('isExistsGrantedGroupFor is return resolve(false);');
  1078. return resolve(false);
  1079. }
  1080. return pageRelations.map(pageRelation => UserGroupRelation.isRelatedUserForGroup(userData, pageRelation.relatedGroup)
  1081. .then(function (checkResult) {
  1082. return resolve(checkResult);
  1083. })
  1084. .catch((err) => {
  1085. return reject(err);
  1086. }));
  1087. })
  1088. .catch((err) => {
  1089. return reject(err);
  1090. });
  1091. });
  1092. }
  1093. /**
  1094. * return path that added slash to the end for specified path
  1095. */
  1096. pageSchema.statics.addSlashOfEnd = function(path) {
  1097. let returnPath = path;
  1098. if (!path.match(/\/$/)) {
  1099. returnPath += '/';
  1100. }
  1101. return returnPath;
  1102. }
  1103. pageSchema.statics.GRANT_PUBLIC = GRANT_PUBLIC;
  1104. pageSchema.statics.GRANT_RESTRICTED = GRANT_RESTRICTED;
  1105. pageSchema.statics.GRANT_SPECIFIED = GRANT_SPECIFIED;
  1106. pageSchema.statics.GRANT_OWNER = GRANT_OWNER;
  1107. pageSchema.statics.PAGE_GRANT_ERROR = PAGE_GRANT_ERROR;
  1108. return mongoose.model('Page', pageSchema);
  1109. };