page.js 38 KB

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