page.js 33 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168
  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. // add slash to the last
  519. path = Page.addSlashOfEnd(path);
  520. // escape
  521. path = escapeStringRegexp(path);
  522. return Page.findListByStartWith(path, userData, option);
  523. };
  524. /**
  525. * find pages that start with `path`
  526. *
  527. * If `path` has `/` at the end, returns '{path}/*' and '{path}' self.
  528. * If `path` doesn't have `/` at the end, returns '{path}*'
  529. */
  530. pageSchema.statics.findListByStartWith = function(path, userData, option) {
  531. var Page = this;
  532. var User = crowi.model('User');
  533. if (!option) {
  534. option = {sort: 'updatedAt', desc: -1, offset: 0, limit: 50};
  535. }
  536. var opt = {
  537. sort: option.sort || 'updatedAt',
  538. desc: option.desc || -1,
  539. offset: option.offset || 0,
  540. limit: option.limit || 50
  541. };
  542. var sortOpt = {};
  543. sortOpt[opt.sort] = opt.desc;
  544. var isPopulateRevisionBody = option.isPopulateRevisionBody || false;
  545. return new Promise(function(resolve, reject) {
  546. var q = Page.generateQueryToListByStartWith(path, userData, option)
  547. .sort(sortOpt)
  548. .skip(opt.offset)
  549. .limit(opt.limit);
  550. // retrieve revision data
  551. if (isPopulateRevisionBody) {
  552. q = q.populate('revision');
  553. }
  554. else {
  555. q = q.populate('revision', '-body'); // exclude body
  556. }
  557. q.exec()
  558. .then(function(pages) {
  559. Page.populate(pages, {path: 'revision.author', model: 'User', select: User.USER_PUBLIC_FIELDS})
  560. .then(resolve)
  561. .catch(reject);
  562. })
  563. });
  564. };
  565. /**
  566. * generate the query to find the page that is match with `path` and its descendants
  567. */
  568. pageSchema.statics.generateQueryToListWithDescendants = function(path, userData, option) {
  569. var Page = this;
  570. // add slash to the last
  571. path = Page.addSlashOfEnd(path);
  572. // escape
  573. path = escapeStringRegexp(path);
  574. return Page.generateQueryToListByStartWith(path, userData, option);
  575. };
  576. /**
  577. * generate the query to find pages that start with `path`
  578. *
  579. * If `path` has `/` at the end, returns '{path}/*' and '{path}' self.
  580. * If `path` doesn't have `/` at the end, returns '{path}*'
  581. */
  582. pageSchema.statics.generateQueryToListByStartWith = function(path, userData, option) {
  583. var Page = this;
  584. var pathCondition = [];
  585. var includeDeletedPage = option.includeDeletedPage || false;
  586. var queryReg = new RegExp('^' + path);
  587. pathCondition.push({path: queryReg});
  588. if (path.match(/\/$/)) {
  589. debug('Page list by ending with /, so find also upper level page');
  590. pathCondition.push({path: path.substr(0, path.length -1)});
  591. }
  592. var q = Page.find({
  593. redirectTo: null,
  594. $or: [
  595. {grant: null},
  596. {grant: GRANT_PUBLIC},
  597. {grant: GRANT_RESTRICTED, grantedUsers: userData._id},
  598. {grant: GRANT_SPECIFIED, grantedUsers: userData._id},
  599. {grant: GRANT_OWNER, grantedUsers: userData._id},
  600. ],})
  601. .and({
  602. $or: pathCondition
  603. });
  604. if (!includeDeletedPage) {
  605. q.and({
  606. $or: [
  607. {status: null},
  608. {status: STATUS_PUBLISHED},
  609. ],
  610. });
  611. }
  612. return q;
  613. }
  614. pageSchema.statics.updatePageProperty = function(page, updateData) {
  615. var Page = this;
  616. return new Promise(function(resolve, reject) {
  617. // TODO foreach して save
  618. Page.update({_id: page._id}, {$set: updateData}, function(err, data) {
  619. if (err) {
  620. return reject(err);
  621. }
  622. return resolve(data);
  623. });
  624. });
  625. };
  626. pageSchema.statics.updateGrant = function(page, grant, userData) {
  627. var Page = this;
  628. return new Promise(function(resolve, reject) {
  629. page.grant = grant;
  630. if (grant == GRANT_PUBLIC) {
  631. page.grantedUsers = [];
  632. } else {
  633. page.grantedUsers = [];
  634. page.grantedUsers.push(userData._id);
  635. }
  636. page.save(function(err, data) {
  637. debug('Page.updateGrant, saved grantedUsers.', err, data);
  638. if (err) {
  639. return reject(err);
  640. }
  641. return resolve(data);
  642. });
  643. });
  644. };
  645. // Instance method でいいのでは
  646. pageSchema.statics.pushToGrantedUsers = function(page, userData) {
  647. return new Promise(function(resolve, reject) {
  648. if (!page.grantedUsers || !Array.isArray(page.grantedUsers)) {
  649. page.grantedUsers = [];
  650. }
  651. page.grantedUsers.push(userData);
  652. page.save(function(err, data) {
  653. if (err) {
  654. return reject(err);
  655. }
  656. return resolve(data);
  657. });
  658. });
  659. };
  660. pageSchema.statics.pushRevision = function(pageData, newRevision, user) {
  661. var isCreate = false;
  662. if (pageData.revision === undefined) {
  663. debug('pushRevision on Create');
  664. isCreate = true;
  665. }
  666. return new Promise(function(resolve, reject) {
  667. newRevision.save(function(err, newRevision) {
  668. if (err) {
  669. debug('Error on saving revision', err);
  670. return reject(err);
  671. }
  672. debug('Successfully saved new revision', newRevision);
  673. pageData.revision = newRevision;
  674. pageData.lastUpdateUser = user;
  675. pageData.updatedAt = Date.now();
  676. pageData.save(function(err, data) {
  677. if (err) {
  678. // todo: remove new revision?
  679. debug('Error on save page data (after push revision)', err);
  680. return reject(err);
  681. }
  682. resolve(data);
  683. if (!isCreate) {
  684. debug('pushRevision on Update');
  685. }
  686. });
  687. });
  688. });
  689. };
  690. pageSchema.statics.create = function(path, body, user, options) {
  691. var Page = this
  692. , Revision = crowi.model('Revision')
  693. , format = options.format || 'markdown'
  694. , grant = options.grant || GRANT_PUBLIC
  695. , redirectTo = options.redirectTo || null;
  696. // force public
  697. if (isPortalPath(path)) {
  698. grant = GRANT_PUBLIC;
  699. }
  700. return new Promise(function(resolve, reject) {
  701. Page.findOne({path: path}, function(err, pageData) {
  702. if (pageData) {
  703. return reject(new Error('Cannot create new page to existed path'));
  704. }
  705. var newPage = new Page();
  706. newPage.path = path;
  707. newPage.creator = user;
  708. newPage.lastUpdateUser = user;
  709. newPage.createdAt = Date.now();
  710. newPage.updatedAt = Date.now();
  711. newPage.redirectTo = redirectTo;
  712. newPage.grant = grant;
  713. newPage.status = STATUS_PUBLISHED;
  714. newPage.grantedUsers = [];
  715. newPage.grantedUsers.push(user);
  716. newPage.save(function (err, newPage) {
  717. if (err) {
  718. return reject(err);
  719. }
  720. var newRevision = Revision.prepareRevision(newPage, body, user, {format: format});
  721. Page.pushRevision(newPage, newRevision, user).then(function(data) {
  722. resolve(data);
  723. pageEvent.emit('create', data, user);
  724. }).catch(function(err) {
  725. debug('Push Revision Error on create page', err);
  726. return reject(err);
  727. });
  728. });
  729. });
  730. });
  731. };
  732. pageSchema.statics.updatePage = function(pageData, body, user, options) {
  733. var Page = this
  734. , Revision = crowi.model('Revision')
  735. , grant = options.grant || null
  736. ;
  737. // update existing page
  738. var newRevision = Revision.prepareRevision(pageData, body, user);
  739. return new Promise(function(resolve, reject) {
  740. Page.pushRevision(pageData, newRevision, user)
  741. .then(function(revision) {
  742. if (grant != pageData.grant) {
  743. return Page.updateGrant(pageData, grant, user).then(function(data) {
  744. debug('Page grant update:', data);
  745. resolve(data);
  746. pageEvent.emit('update', data, user);
  747. });
  748. } else {
  749. resolve(pageData);
  750. pageEvent.emit('update', pageData, user);
  751. }
  752. }).catch(function(err) {
  753. debug('Error on update', err);
  754. debug('Error on update', err.stack);
  755. });
  756. });
  757. };
  758. pageSchema.statics.deletePage = function(pageData, user, options) {
  759. var Page = this
  760. , newPath = Page.getDeletedPageName(pageData.path)
  761. ;
  762. if (Page.isDeletableName(pageData.path)) {
  763. return new Promise(function(resolve, reject) {
  764. Page.updatePageProperty(pageData, {status: STATUS_DELETED, lastUpdateUser: user})
  765. .then(function(data) {
  766. pageData.status = STATUS_DELETED;
  767. // ページ名が /trash/ 以下に存在する場合、おかしなことになる
  768. // が、 /trash 以下にページが有るのは、個別に作っていたケースのみ。
  769. // 一応しばらく前から uncreatable pages になっているのでこれでいいことにする
  770. debug('Deleted the page, and rename it', pageData.path, newPath);
  771. return Page.rename(pageData, newPath, user, {createRedirectPage: true})
  772. }).then(function(pageData) {
  773. resolve(pageData);
  774. }).catch(reject);
  775. });
  776. } else {
  777. return Promise.reject('Page is not deletable.');
  778. }
  779. };
  780. pageSchema.statics.deletePageRecursively = function (pageData, user, options) {
  781. var Page = this
  782. , path = pageData.path
  783. , options = options || {}
  784. ;
  785. return new Promise(function (resolve, reject) {
  786. Page
  787. .generateQueryToListWithDescendants(path, user, options)
  788. .then(function (pages) {
  789. Promise.all(pages.map(function (page) {
  790. return Page.deletePage(page, user, options);
  791. }))
  792. .then(function (data) {
  793. return resolve(pageData);
  794. });
  795. });
  796. });
  797. };
  798. pageSchema.statics.revertDeletedPage = function(pageData, user, options) {
  799. var Page = this
  800. , newPath = Page.getRevertDeletedPageName(pageData.path)
  801. ;
  802. // 削除時、元ページの path には必ず redirectTo 付きで、ページが作成される。
  803. // そのため、そいつは削除してOK
  804. // が、redirectTo ではないページが存在している場合それは何かがおかしい。(データ補正が必要)
  805. return new Promise(function(resolve, reject) {
  806. Page.findPageByPath(newPath)
  807. .then(function(originPageData) {
  808. if (originPageData.redirectTo !== pageData.path) {
  809. throw new Error('The new page of to revert is exists and the redirect path of the page is not the deleted page.');
  810. }
  811. return Page.completelyDeletePage(originPageData);
  812. }).then(function(done) {
  813. return Page.updatePageProperty(pageData, {status: STATUS_PUBLISHED, lastUpdateUser: user})
  814. }).then(function(done) {
  815. pageData.status = STATUS_PUBLISHED;
  816. debug('Revert deleted the page, and rename again it', pageData, newPath);
  817. return Page.rename(pageData, newPath, user, {})
  818. }).then(function(done) {
  819. pageData.path = newPath;
  820. resolve(pageData);
  821. }).catch(reject);
  822. });
  823. };
  824. pageSchema.statics.revertDeletedPageRecursively = function (pageData, user, options) {
  825. var Page = this
  826. , path = pageData.path
  827. , options = options || { includeDeletedPage: true}
  828. ;
  829. return new Promise(function (resolve, reject) {
  830. Page
  831. .generateQueryToListWithDescendants(path, user, options)
  832. .then(function (pages) {
  833. Promise.all(pages.map(function (page) {
  834. return Page.revertDeletedPage(page, user, options);
  835. }))
  836. .then(function (data) {
  837. return resolve(data[0]);
  838. });
  839. });
  840. });
  841. };
  842. /**
  843. * This is danger.
  844. */
  845. pageSchema.statics.completelyDeletePage = function(pageData, user, options) {
  846. // Delete Bookmarks, Attachments, Revisions, Pages and emit delete
  847. var Bookmark = crowi.model('Bookmark')
  848. , Attachment = crowi.model('Attachment')
  849. , Comment = crowi.model('Comment')
  850. , Revision = crowi.model('Revision')
  851. , Page = this
  852. , pageId = pageData._id
  853. ;
  854. debug('Completely delete', pageData.path);
  855. return new Promise(function(resolve, reject) {
  856. Bookmark.removeBookmarksByPageId(pageId)
  857. .then(function(done) {
  858. }).then(function(done) {
  859. return Attachment.removeAttachmentsByPageId(pageId);
  860. }).then(function(done) {
  861. return Comment.removeCommentsByPageId(pageId);
  862. }).then(function(done) {
  863. return Revision.removeRevisionsByPath(pageData.path);
  864. }).then(function(done) {
  865. return Page.removePageById(pageId);
  866. }).then(function(done) {
  867. return Page.removeRedirectOriginPageByPath(pageData.path);
  868. }).then(function(done) {
  869. pageEvent.emit('delete', pageData, user); // update as renamed page
  870. resolve(pageData);
  871. }).catch(reject);
  872. });
  873. };
  874. pageSchema.statics.completelyDeletePageRecursively = function (pageData, user, options) {
  875. // Delete Bookmarks, Attachments, Revisions, Pages and emit delete
  876. var Page = this
  877. , path = pageData.path
  878. , options = options || { includeDeletedPage: true }
  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.completelyDeletePage(page, user, options);
  886. }))
  887. .then(function (data) {
  888. return resolve(data[0]);
  889. });
  890. });
  891. });
  892. };
  893. pageSchema.statics.removePageById = function(pageId) {
  894. var Page = this;
  895. return new Promise(function(resolve, reject) {
  896. Page.remove({_id: pageId}, function(err, done) {
  897. debug('Remove phisiaclly, the page', pageId, err, done);
  898. if (err) {
  899. return reject(err);
  900. }
  901. resolve(done);
  902. });
  903. });
  904. };
  905. pageSchema.statics.removePageByPath = function(pagePath) {
  906. var Page = this;
  907. return Page.findPageByPath(pagePath)
  908. .then(function(pageData) {
  909. return Page.removePageById(pageData.id);
  910. });
  911. };
  912. /**
  913. * remove the page that is redirecting to specified `pagePath` recursively
  914. * ex: when
  915. * '/page1' redirects to '/page2' and
  916. * '/page2' redirects to '/page3'
  917. * and given '/page3',
  918. * '/page1' and '/page2' will be removed
  919. *
  920. * @param {string} pagePath
  921. */
  922. pageSchema.statics.removeRedirectOriginPageByPath = function(pagePath) {
  923. var Page = this;
  924. return Page.findPageByRedirectTo(pagePath)
  925. .then((redirectOriginPageData) => {
  926. // remove
  927. return Page.removePageById(redirectOriginPageData.id)
  928. // remove recursive
  929. .then(() => {
  930. return Page.removeRedirectOriginPageByPath(redirectOriginPageData.path)
  931. });
  932. })
  933. .catch((err) => {
  934. // do nothing if origin page doesn't exist
  935. return Promise.resolve();
  936. })
  937. };
  938. pageSchema.statics.rename = function(pageData, newPagePath, user, options) {
  939. var Page = this
  940. , Revision = crowi.model('Revision')
  941. , path = pageData.path
  942. , createRedirectPage = options.createRedirectPage || 0
  943. , moveUnderTrees = options.moveUnderTrees || 0;
  944. return new Promise(function(resolve, reject) {
  945. // pageData の path を変更
  946. Page.updatePageProperty(pageData, {updatedAt: Date.now(), path: newPagePath, lastUpdateUser: user})
  947. .then(function(data) {
  948. // reivisions の path を変更
  949. return Revision.updateRevisionListByPath(path, {path: newPagePath}, {})
  950. }).then(function(data) {
  951. pageData.path = newPagePath;
  952. if (createRedirectPage) {
  953. var body = 'redirect ' + newPagePath;
  954. Page.create(path, body, user, {redirectTo: newPagePath}).then(resolve).catch(reject);
  955. } else {
  956. resolve(data);
  957. }
  958. pageEvent.emit('update', pageData, user); // update as renamed page
  959. });
  960. });
  961. };
  962. pageSchema.statics.renameRecursively = function(pageData, newPagePathPrefix, user, options) {
  963. var Page = this
  964. , path = pageData.path
  965. , pathRegExp = new RegExp('^' + escapeStringRegexp(path), 'i');
  966. return new Promise(function(resolve, reject) {
  967. Page
  968. .generateQueryToListWithDescendants(path, user, options)
  969. .then(function(pages) {
  970. Promise.all(pages.map(function(page) {
  971. newPagePath = page.path.replace(pathRegExp, newPagePathPrefix);
  972. return Page.rename(page, newPagePath, user, options);
  973. }))
  974. .then(function() {
  975. pageData.path = newPagePathPrefix;
  976. return resolve();
  977. });
  978. });
  979. });
  980. };
  981. pageSchema.statics.getHistories = function() {
  982. // TODO
  983. return;
  984. };
  985. /**
  986. * return path that added slash to the end for specified path
  987. */
  988. pageSchema.statics.addSlashOfEnd = function(path) {
  989. let returnPath = path;
  990. if (!path.match(/\/$/)) {
  991. returnPath += '/';
  992. }
  993. return returnPath;
  994. }
  995. pageSchema.statics.GRANT_PUBLIC = GRANT_PUBLIC;
  996. pageSchema.statics.GRANT_RESTRICTED = GRANT_RESTRICTED;
  997. pageSchema.statics.GRANT_SPECIFIED = GRANT_SPECIFIED;
  998. pageSchema.statics.GRANT_OWNER = GRANT_OWNER;
  999. pageSchema.statics.PAGE_GRANT_ERROR = PAGE_GRANT_ERROR;
  1000. return mongoose.model('Page', pageSchema);
  1001. };