page.js 37 KB

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