page.js 34 KB

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