page.js 38 KB

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