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