page.js 39 KB

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