page.js 38 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286
  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.checkIsExistsRelationForPageAndGroup(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, function (err, relationData) {
  705. if (err) {
  706. return reject(err);
  707. }
  708. });
  709. }
  710. return Promise.resolve();
  711. });
  712. }
  713. else {
  714. PageGroupRelation.removeAllByPage(page, function (err, result) {
  715. if (err) {
  716. return reject(err);
  717. }
  718. });
  719. }
  720. return resolve(data);
  721. });
  722. });
  723. };
  724. // Instance method でいいのでは
  725. pageSchema.statics.pushToGrantedUsers = function(page, userData) {
  726. return new Promise(function(resolve, reject) {
  727. if (!page.grantedUsers || !Array.isArray(page.grantedUsers)) {
  728. page.grantedUsers = [];
  729. }
  730. page.grantedUsers.push(userData);
  731. page.save(function(err, data) {
  732. if (err) {
  733. return reject(err);
  734. }
  735. return resolve(data);
  736. });
  737. });
  738. };
  739. pageSchema.statics.pushRevision = function(pageData, newRevision, user) {
  740. var isCreate = false;
  741. if (pageData.revision === undefined) {
  742. debug('pushRevision on Create');
  743. isCreate = true;
  744. }
  745. return new Promise(function(resolve, reject) {
  746. newRevision.save(function(err, newRevision) {
  747. if (err) {
  748. debug('Error on saving revision', err);
  749. return reject(err);
  750. }
  751. debug('Successfully saved new revision', newRevision);
  752. pageData.revision = newRevision;
  753. pageData.lastUpdateUser = user;
  754. pageData.updatedAt = Date.now();
  755. pageData.save(function(err, data) {
  756. if (err) {
  757. // todo: remove new revision?
  758. debug('Error on save page data (after push revision)', err);
  759. return reject(err);
  760. }
  761. resolve(data);
  762. if (!isCreate) {
  763. debug('pushRevision on Update');
  764. }
  765. });
  766. });
  767. });
  768. };
  769. pageSchema.statics.create = function(path, body, user, options) {
  770. var Page = this
  771. , Revision = crowi.model('Revision')
  772. , format = options.format || 'markdown'
  773. , grant = options.grant || GRANT_PUBLIC
  774. , redirectTo = options.redirectTo || null
  775. , grantUserGroupId = options.grantUserGroupId || null;
  776. // force public
  777. if (isPortalPath(path)) {
  778. grant = GRANT_PUBLIC;
  779. }
  780. return new Promise(function(resolve, reject) {
  781. Page.findOne({path: path}, function(err, pageData) {
  782. if (pageData) {
  783. return reject(new Error('Cannot create new page to existed path'));
  784. }
  785. var newPage = new Page();
  786. newPage.path = path;
  787. newPage.creator = user;
  788. newPage.lastUpdateUser = user;
  789. newPage.createdAt = Date.now();
  790. newPage.updatedAt = Date.now();
  791. newPage.redirectTo = redirectTo;
  792. newPage.grant = grant;
  793. newPage.status = STATUS_PUBLISHED;
  794. newPage.grantedUsers = [];
  795. newPage.grantedUsers.push(user);
  796. newPage.save(function (err, newPage) {
  797. if (err) {
  798. return reject(err);
  799. }
  800. if (newPage.grant == Page.GRANT_USER_GROUP && grantUserGroupId != null) {
  801. PageGroupRelation.createRelation(grantUserGroupId, newPage, function (err, relationData) {
  802. if (err) {
  803. return reject(err);
  804. }
  805. });
  806. }
  807. var newRevision = Revision.prepareRevision(newPage, body, user, {format: format});
  808. Page.pushRevision(newPage, newRevision, user).then(function(data) {
  809. resolve(data);
  810. pageEvent.emit('create', data, user);
  811. }).catch(function(err) {
  812. debug('Push Revision Error on create page', err);
  813. return reject(err);
  814. });
  815. });
  816. });
  817. });
  818. };
  819. pageSchema.statics.updatePage = function(pageData, body, user, options) {
  820. var Page = this
  821. , Revision = crowi.model('Revision')
  822. , grant = options.grant || null
  823. , grantUserGroupId = options.grantUserGroupId || null
  824. ;
  825. // update existing page
  826. var newRevision = Revision.prepareRevision(pageData, body, user);
  827. return new Promise(function(resolve, reject) {
  828. Page.pushRevision(pageData, newRevision, user)
  829. .then(function(revision) {
  830. if (grant != pageData.grant) {
  831. return Page.updateGrant(pageData, grant, user, grantUserGroupId).then(function(data) {
  832. debug('Page grant update:', data);
  833. resolve(data);
  834. pageEvent.emit('update', data, user);
  835. });
  836. } else {
  837. resolve(pageData);
  838. pageEvent.emit('update', pageData, user);
  839. }
  840. }).catch(function(err) {
  841. debug('Error on update', err);
  842. debug('Error on update', err.stack);
  843. });
  844. });
  845. };
  846. pageSchema.statics.deletePage = function(pageData, user, options) {
  847. var Page = this
  848. , newPath = Page.getDeletedPageName(pageData.path)
  849. ;
  850. if (Page.isDeletableName(pageData.path)) {
  851. return new Promise(function(resolve, reject) {
  852. Page.updatePageProperty(pageData, {status: STATUS_DELETED, lastUpdateUser: user})
  853. .then(function(data) {
  854. pageData.status = STATUS_DELETED;
  855. // ページ名が /trash/ 以下に存在する場合、おかしなことになる
  856. // が、 /trash 以下にページが有るのは、個別に作っていたケースのみ。
  857. // 一応しばらく前から uncreatable pages になっているのでこれでいいことにする
  858. debug('Deleted the page, and rename it', pageData.path, newPath);
  859. return Page.rename(pageData, newPath, user, {createRedirectPage: true})
  860. }).then(function(pageData) {
  861. resolve(pageData);
  862. }).catch(reject);
  863. });
  864. } else {
  865. return Promise.reject('Page is not deletable.');
  866. }
  867. };
  868. pageSchema.statics.deletePageRecursively = function (pageData, user, options) {
  869. var Page = this
  870. , path = pageData.path
  871. , options = options || {}
  872. ;
  873. return new Promise(function (resolve, reject) {
  874. Page
  875. .generateQueryToListWithDescendants(path, user, options)
  876. .then(function (pages) {
  877. Promise.all(pages.map(function (page) {
  878. return Page.deletePage(page, user, options);
  879. }))
  880. .then(function (data) {
  881. return resolve(pageData);
  882. });
  883. });
  884. });
  885. };
  886. pageSchema.statics.revertDeletedPage = function(pageData, user, options) {
  887. var Page = this
  888. , newPath = Page.getRevertDeletedPageName(pageData.path)
  889. ;
  890. // 削除時、元ページの path には必ず redirectTo 付きで、ページが作成される。
  891. // そのため、そいつは削除してOK
  892. // が、redirectTo ではないページが存在している場合それは何かがおかしい。(データ補正が必要)
  893. return new Promise(function(resolve, reject) {
  894. Page.findPageByPath(newPath)
  895. .then(function(originPageData) {
  896. if (originPageData.redirectTo !== pageData.path) {
  897. throw new Error('The new page of to revert is exists and the redirect path of the page is not the deleted page.');
  898. }
  899. return Page.completelyDeletePage(originPageData);
  900. }).then(function(done) {
  901. return Page.updatePageProperty(pageData, {status: STATUS_PUBLISHED, lastUpdateUser: user})
  902. }).then(function(done) {
  903. pageData.status = STATUS_PUBLISHED;
  904. debug('Revert deleted the page, and rename again it', pageData, newPath);
  905. return Page.rename(pageData, newPath, user, {})
  906. }).then(function(done) {
  907. pageData.path = newPath;
  908. resolve(pageData);
  909. }).catch(reject);
  910. });
  911. };
  912. pageSchema.statics.revertDeletedPageRecursively = function (pageData, user, options) {
  913. var Page = this
  914. , path = pageData.path
  915. , options = options || { includeDeletedPage: true}
  916. ;
  917. return new Promise(function (resolve, reject) {
  918. Page
  919. .generateQueryToListWithDescendants(path, user, options)
  920. .then(function (pages) {
  921. Promise.all(pages.map(function (page) {
  922. return Page.revertDeletedPage(page, user, options);
  923. }))
  924. .then(function (data) {
  925. return resolve(data[0]);
  926. });
  927. });
  928. });
  929. };
  930. /**
  931. * This is danger.
  932. */
  933. pageSchema.statics.completelyDeletePage = function(pageData, user, options) {
  934. // Delete Bookmarks, Attachments, Revisions, Pages and emit delete
  935. var Bookmark = crowi.model('Bookmark')
  936. , Attachment = crowi.model('Attachment')
  937. , Comment = crowi.model('Comment')
  938. , Revision = crowi.model('Revision')
  939. , Page = this
  940. , pageId = pageData._id
  941. ;
  942. debug('Completely delete', pageData.path);
  943. return new Promise(function(resolve, reject) {
  944. Bookmark.removeBookmarksByPageId(pageId)
  945. .then(function(done) {
  946. }).then(function(done) {
  947. return Attachment.removeAttachmentsByPageId(pageId);
  948. }).then(function(done) {
  949. return Comment.removeCommentsByPageId(pageId);
  950. }).then(function(done) {
  951. return Revision.removeRevisionsByPath(pageData.path);
  952. }).then(function(done) {
  953. return Page.removePageById(pageId);
  954. }).then(function(done) {
  955. return Page.removeRedirectOriginPageByPath(pageData.path);
  956. }).then(function(done) {
  957. pageEvent.emit('delete', pageData, user); // update as renamed page
  958. resolve(pageData);
  959. }).catch(reject);
  960. });
  961. };
  962. pageSchema.statics.completelyDeletePageRecursively = function (pageData, user, options) {
  963. // Delete Bookmarks, Attachments, Revisions, Pages and emit delete
  964. var Page = this
  965. , path = pageData.path
  966. , options = options || { includeDeletedPage: true }
  967. ;
  968. return new Promise(function (resolve, reject) {
  969. Page
  970. .generateQueryToListWithDescendants(path, user, options)
  971. .then(function (pages) {
  972. Promise.all(pages.map(function (page) {
  973. return Page.completelyDeletePage(page, user, options);
  974. }))
  975. .then(function (data) {
  976. return resolve(data[0]);
  977. });
  978. });
  979. });
  980. };
  981. pageSchema.statics.removePageById = function(pageId) {
  982. var Page = this;
  983. return new Promise(function(resolve, reject) {
  984. Page.remove({_id: pageId}, function(err, done) {
  985. debug('Remove phisiaclly, the page', pageId, err, done);
  986. if (err) {
  987. return reject(err);
  988. }
  989. resolve(done);
  990. });
  991. });
  992. };
  993. pageSchema.statics.removePageByPath = function(pagePath) {
  994. var Page = this;
  995. return Page.findPageByPath(pagePath)
  996. .then(function(pageData) {
  997. return Page.removePageById(pageData.id);
  998. });
  999. };
  1000. /**
  1001. * remove the page that is redirecting to specified `pagePath` recursively
  1002. * ex: when
  1003. * '/page1' redirects to '/page2' and
  1004. * '/page2' redirects to '/page3'
  1005. * and given '/page3',
  1006. * '/page1' and '/page2' will be removed
  1007. *
  1008. * @param {string} pagePath
  1009. */
  1010. pageSchema.statics.removeRedirectOriginPageByPath = function(pagePath) {
  1011. var Page = this;
  1012. return Page.findPageByRedirectTo(pagePath)
  1013. .then((redirectOriginPageData) => {
  1014. // remove
  1015. return Page.removePageById(redirectOriginPageData.id)
  1016. // remove recursive
  1017. .then(() => {
  1018. return Page.removeRedirectOriginPageByPath(redirectOriginPageData.path)
  1019. });
  1020. })
  1021. .catch((err) => {
  1022. // do nothing if origin page doesn't exist
  1023. return Promise.resolve();
  1024. })
  1025. };
  1026. pageSchema.statics.rename = function(pageData, newPagePath, user, options) {
  1027. var Page = this
  1028. , Revision = crowi.model('Revision')
  1029. , path = pageData.path
  1030. , createRedirectPage = options.createRedirectPage || 0
  1031. , moveUnderTrees = options.moveUnderTrees || 0;
  1032. return new Promise(function(resolve, reject) {
  1033. // pageData の path を変更
  1034. Page.updatePageProperty(pageData, {updatedAt: Date.now(), path: newPagePath, lastUpdateUser: user})
  1035. .then(function(data) {
  1036. // reivisions の path を変更
  1037. return Revision.updateRevisionListByPath(path, {path: newPagePath}, {})
  1038. }).then(function(data) {
  1039. pageData.path = newPagePath;
  1040. if (createRedirectPage) {
  1041. var body = 'redirect ' + newPagePath;
  1042. Page.create(path, body, user, {redirectTo: newPagePath}).then(resolve).catch(reject);
  1043. } else {
  1044. resolve(data);
  1045. }
  1046. pageEvent.emit('update', pageData, user); // update as renamed page
  1047. });
  1048. });
  1049. };
  1050. pageSchema.statics.renameRecursively = function(pageData, newPagePathPrefix, user, options) {
  1051. var Page = this
  1052. , path = pageData.path
  1053. , pathRegExp = new RegExp('^' + escapeStringRegexp(path), 'i');
  1054. return new Promise(function(resolve, reject) {
  1055. Page
  1056. .generateQueryToListWithDescendants(path, user, options)
  1057. .then(function(pages) {
  1058. Promise.all(pages.map(function(page) {
  1059. newPagePath = page.path.replace(pathRegExp, newPagePathPrefix);
  1060. return Page.rename(page, newPagePath, user, options);
  1061. }))
  1062. .then(function() {
  1063. pageData.path = newPagePathPrefix;
  1064. return resolve();
  1065. });
  1066. });
  1067. });
  1068. };
  1069. pageSchema.statics.getHistories = function() {
  1070. // TODO
  1071. return;
  1072. };
  1073. // 指定ページに紐づくユーザグループに、対象のユーザが含まれるかを確認
  1074. pageSchema.statics.isExistsGrantedGroupFor = function(pageData, userData) {
  1075. var PageGroupRelation = crowi.model('PageGroupRelation');
  1076. var UserGroupRelation = crowi.model('UserGroupRelation');
  1077. debug('isExistsGrantedGroupFor is called.');
  1078. return new Promise(function (resolve, reject) {
  1079. PageGroupRelation.findByPage(pageData)
  1080. .then(function (pageRelation) {
  1081. debug('PageGroupRelation.findByPage result is ', pageRelation);
  1082. if (pageRelation == null) {
  1083. debug('isExistsGrantedGroupFor is return resolve(false);');
  1084. return resolve(false);
  1085. }
  1086. return UserGroupRelation.checkIsRelatedUserForGroup(userData, pageRelation.relatedGroup)
  1087. .then(function (checkResult) {
  1088. return resolve(checkResult);
  1089. })
  1090. .catch((err) => {
  1091. return reject(err);
  1092. });
  1093. })
  1094. .catch((err) => {
  1095. return reject(err);
  1096. });
  1097. });
  1098. }
  1099. /**
  1100. * return path that added slash to the end for specified path
  1101. */
  1102. pageSchema.statics.addSlashOfEnd = function(path) {
  1103. let returnPath = path;
  1104. if (!path.match(/\/$/)) {
  1105. returnPath += '/';
  1106. }
  1107. return returnPath;
  1108. }
  1109. pageSchema.statics.GRANT_PUBLIC = GRANT_PUBLIC;
  1110. pageSchema.statics.GRANT_RESTRICTED = GRANT_RESTRICTED;
  1111. pageSchema.statics.GRANT_SPECIFIED = GRANT_SPECIFIED;
  1112. pageSchema.statics.GRANT_OWNER = GRANT_OWNER;
  1113. pageSchema.statics.PAGE_GRANT_ERROR = PAGE_GRANT_ERROR;
  1114. return mongoose.model('Page', pageSchema);
  1115. };