page.js 34 KB

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