page.js 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356
  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. console.log('regexp', regexpList)
  468. return Page
  469. .find({path: {$in: regexpList}})
  470. .then(templates => {
  471. templateInfo.childrenTemplateExists = (assignTemplateByType(templates, path, '_') ? true : false);
  472. templateInfo.decendantsTemplateExists = (assignTemplateByType(templates, path, '__') ? true : false);
  473. return templateInfo;
  474. });
  475. };
  476. /**
  477. * find all templates applicable to the new page
  478. */
  479. pageSchema.statics.findTemplate = function(path) {
  480. const Page = this;
  481. const templatePath = cutOffLastSlash(path);
  482. const pathList = generatePathsOnTree(templatePath, []);
  483. const regexpList = pathList.map(path => new RegExp(`^${path}/_{1,2}template$`));
  484. return Page
  485. .find({path: {$in: regexpList}})
  486. .populate({path: 'revision', model: 'Revision'})
  487. .then(templates => {
  488. return fetchTemplate(templates, templatePath);
  489. });
  490. };
  491. const cutOffLastSlash = path => {
  492. const lastSlash = path.lastIndexOf('/');
  493. return path.substr(0, lastSlash);
  494. };
  495. const generatePathsOnTree = (path, pathList) => {
  496. pathList.push(path);
  497. if (path === '') {
  498. return pathList;
  499. }
  500. const newPath = cutOffLastSlash(path);
  501. return generatePathsOnTree(newPath, pathList);
  502. };
  503. const assignTemplateByType = (templates, path, type) => {
  504. for (let i = 0; i < templates.length; i++) {
  505. if (templates[i].path === `${path}/${type}template`) {
  506. return templates[i];
  507. }
  508. }
  509. };
  510. const assignDecendantsTemplate = (decendantsTemplates, path) => {
  511. const decendantsTemplate = assignTemplateByType(decendantsTemplates, path, '__');
  512. if (decendantsTemplate) {
  513. return decendantsTemplate;
  514. }
  515. if (path === '') {
  516. return;
  517. }
  518. const newPath = cutOffLastSlash(path);
  519. return assignDecendantsTemplate(decendantsTemplates, newPath);
  520. };
  521. const fetchTemplate = (templates, templatePath) => {
  522. let templateBody;
  523. /**
  524. * get children template
  525. * __tempate: applicable only to immediate decendants
  526. */
  527. const childrenTemplate = assignTemplateByType(templates, templatePath, '_');
  528. /**
  529. * get decendants templates
  530. * _tempate: applicable to all pages under
  531. */
  532. const decendantsTemplate = assignDecendantsTemplate(templates, templatePath);
  533. if (childrenTemplate) {
  534. templateBody = childrenTemplate.revision.body;
  535. }
  536. else if (decendantsTemplate) {
  537. templateBody = decendantsTemplate.revision.body;
  538. }
  539. return templateBody;
  540. };
  541. // find page by path
  542. pageSchema.statics.findPageByPath = function(path) {
  543. if (path == null) {
  544. return null;
  545. }
  546. return this.findOne({path});
  547. };
  548. pageSchema.statics.findListByPageIds = function(ids, options) {
  549. var Page = this;
  550. var User = crowi.model('User');
  551. var options = options || {}
  552. , limit = options.limit || 50
  553. , offset = options.skip || 0
  554. ;
  555. return new Promise(function(resolve, reject) {
  556. Page
  557. .find({ _id: { $in: ids }, grant: GRANT_PUBLIC })
  558. //.sort({createdAt: -1}) // TODO optionize
  559. .skip(offset)
  560. .limit(limit)
  561. .populate([
  562. {path: 'creator', model: 'User', select: User.USER_PUBLIC_FIELDS},
  563. {path: 'revision', model: 'Revision'},
  564. ])
  565. .exec(function(err, pages) {
  566. if (err) {
  567. return reject(err);
  568. }
  569. Page.populate(pages, {path: 'revision.author', model: 'User', select: User.USER_PUBLIC_FIELDS}, function(err, data) {
  570. if (err) {
  571. return reject(err);
  572. }
  573. return resolve(data);
  574. });
  575. });
  576. });
  577. };
  578. pageSchema.statics.findPageByRedirectTo = function(path) {
  579. var Page = this;
  580. return new Promise(function(resolve, reject) {
  581. Page.findOne({redirectTo: path}, function(err, pageData) {
  582. if (err || pageData === null) {
  583. return reject(err);
  584. }
  585. return resolve(pageData);
  586. });
  587. });
  588. };
  589. pageSchema.statics.findListByCreator = function(user, option, currentUser) {
  590. var Page = this;
  591. var User = crowi.model('User');
  592. var limit = option.limit || 50;
  593. var offset = option.offset || 0;
  594. var conditions = {
  595. creator: user._id,
  596. redirectTo: null,
  597. $or: [
  598. {status: null},
  599. {status: STATUS_PUBLISHED},
  600. ],
  601. };
  602. if (!user.equals(currentUser._id)) {
  603. conditions.grant = GRANT_PUBLIC;
  604. }
  605. return new Promise(function(resolve, reject) {
  606. Page
  607. .find(conditions)
  608. .sort({createdAt: -1})
  609. .skip(offset)
  610. .limit(limit)
  611. .populate('revision')
  612. .exec()
  613. .then(function(pages) {
  614. return Page.populate(pages, {path: 'revision.author', model: 'User', select: User.USER_PUBLIC_FIELDS}).then(resolve);
  615. });
  616. });
  617. };
  618. /**
  619. * Bulk get (for internal only)
  620. */
  621. pageSchema.statics.getStreamOfFindAll = function(options) {
  622. var Page = this
  623. , options = options || {}
  624. , publicOnly = options.publicOnly || true
  625. , criteria = {redirectTo: null, }
  626. ;
  627. if (publicOnly) {
  628. criteria.grant = GRANT_PUBLIC;
  629. }
  630. return this.find(criteria)
  631. .populate([
  632. {path: 'creator', model: 'User'},
  633. {path: 'revision', model: 'Revision'},
  634. ])
  635. .sort({updatedAt: -1})
  636. .cursor();
  637. };
  638. /**
  639. * find the page that is match with `path` and its descendants
  640. */
  641. pageSchema.statics.findListWithDescendants = function(path, userData, option) {
  642. var Page = this;
  643. // ignore other pages than descendants
  644. path = Page.addSlashOfEnd(path);
  645. // add option to escape the regex strings
  646. const combinedOption = Object.assign({isRegExpEscapedFromPath: true}, option);
  647. return Page.findListByStartWith(path, userData, combinedOption);
  648. };
  649. /**
  650. * find pages that start with `path`
  651. *
  652. * see the comment of `generateQueryToListByStartWith` function
  653. */
  654. pageSchema.statics.findListByStartWith = function(path, userData, option) {
  655. var Page = this;
  656. var User = crowi.model('User');
  657. if (!option) {
  658. option = {sort: 'updatedAt', desc: -1, offset: 0, limit: 50};
  659. }
  660. var opt = {
  661. sort: option.sort || 'updatedAt',
  662. desc: option.desc || -1,
  663. offset: option.offset || 0,
  664. limit: option.limit || 50
  665. };
  666. var sortOpt = {};
  667. sortOpt[opt.sort] = opt.desc;
  668. var isPopulateRevisionBody = option.isPopulateRevisionBody || false;
  669. return new Promise(function(resolve, reject) {
  670. var q = Page.generateQueryToListByStartWith(path, userData, option)
  671. .sort(sortOpt)
  672. .skip(opt.offset)
  673. .limit(opt.limit);
  674. // retrieve revision data
  675. if (isPopulateRevisionBody) {
  676. q = q.populate('revision');
  677. }
  678. else {
  679. q = q.populate('revision', '-body'); // exclude body
  680. }
  681. q.exec()
  682. .then(function(pages) {
  683. Page.populate(pages, {path: 'revision.author', model: 'User', select: User.USER_PUBLIC_FIELDS})
  684. .then(resolve)
  685. .catch(reject);
  686. });
  687. });
  688. };
  689. /**
  690. * generate the query to find the page that is match with `path` and its descendants
  691. */
  692. pageSchema.statics.generateQueryToListWithDescendants = function(path, userData, option) {
  693. var Page = this;
  694. // ignore other pages than descendants
  695. path = Page.addSlashOfEnd(path);
  696. // add option to escape the regex strings
  697. const combinedOption = Object.assign({isRegExpEscapedFromPath: true}, option);
  698. return Page.generateQueryToListByStartWith(path, userData, combinedOption);
  699. };
  700. /**
  701. * generate the query to find pages that start with `path`
  702. *
  703. * (GROWI) If 'isRegExpEscapedFromPath' is true, `path` should have `/` at the end
  704. * -> returns '{path}/*' and '{path}' self.
  705. * (Crowi) If 'isRegExpEscapedFromPath' is false and `path` has `/` at the end
  706. * -> returns '{path}*'
  707. * (Crowi) If 'isRegExpEscapedFromPath' is false and `path` doesn't have `/` at the end
  708. * -> returns '{path}*'
  709. *
  710. * *option*
  711. * - includeDeletedPage -- if true, search deleted pages (default: false)
  712. * - isRegExpEscapedFromPath -- if true, the regex strings included in `path` is escaped (default: false)
  713. */
  714. pageSchema.statics.generateQueryToListByStartWith = function(path, userData, option) {
  715. var Page = this;
  716. var pathCondition = [];
  717. var includeDeletedPage = option.includeDeletedPage || false;
  718. var isRegExpEscapedFromPath = option.isRegExpEscapedFromPath || false;
  719. /*
  720. * 1. add condition for finding the page completely match with `path` w/o last slash
  721. */
  722. let pathSlashOmitted = path;
  723. if (path.match(/\/$/)) {
  724. pathSlashOmitted = path.substr(0, path.length -1);
  725. pathCondition.push({path: pathSlashOmitted});
  726. }
  727. /*
  728. * 2. add decendants
  729. */
  730. var pattern = (isRegExpEscapedFromPath)
  731. ? escapeStringRegexp(path) // escape
  732. : pathSlashOmitted;
  733. var queryReg = new RegExp('^' + pattern);
  734. pathCondition.push({path: queryReg});
  735. var q = Page.find({
  736. redirectTo: null,
  737. $or: [
  738. {grant: null},
  739. {grant: GRANT_PUBLIC},
  740. {grant: GRANT_RESTRICTED, grantedUsers: userData._id},
  741. {grant: GRANT_SPECIFIED, grantedUsers: userData._id},
  742. {grant: GRANT_OWNER, grantedUsers: userData._id},
  743. {grant: GRANT_USER_GROUP},
  744. ], })
  745. .and({
  746. $or: pathCondition
  747. });
  748. if (!includeDeletedPage) {
  749. q.and({
  750. $or: [
  751. {status: null},
  752. {status: STATUS_PUBLISHED},
  753. ],
  754. });
  755. }
  756. return q;
  757. };
  758. pageSchema.statics.updatePageProperty = function(page, updateData) {
  759. var Page = this;
  760. return new Promise(function(resolve, reject) {
  761. // TODO foreach して save
  762. Page.update({_id: page._id}, {$set: updateData}, function(err, data) {
  763. if (err) {
  764. return reject(err);
  765. }
  766. return resolve(data);
  767. });
  768. });
  769. };
  770. pageSchema.statics.updateGrant = function(page, grant, userData, grantUserGroupId) {
  771. var Page = this;
  772. return new Promise(function(resolve, reject) {
  773. if (grant == GRANT_USER_GROUP && grantUserGroupId == null) {
  774. reject('grant userGroupId is not specified');
  775. }
  776. page.grant = grant;
  777. if (grant == GRANT_PUBLIC || grant == GRANT_USER_GROUP) {
  778. page.grantedUsers = [];
  779. }
  780. else {
  781. page.grantedUsers = [];
  782. page.grantedUsers.push(userData._id);
  783. }
  784. page.save(function(err, data) {
  785. debug('Page.updateGrant, saved grantedUsers.', err, data);
  786. if (err) {
  787. return reject(err);
  788. }
  789. Page.updateGrantUserGroup(page, grant, grantUserGroupId, userData)
  790. .then(() => {
  791. return resolve(data);
  792. });
  793. });
  794. });
  795. };
  796. pageSchema.statics.updateGrantUserGroup = function(page, grant, grantUserGroupId, userData) {
  797. var UserGroupRelation = crowi.model('UserGroupRelation');
  798. var PageGroupRelation = crowi.model('PageGroupRelation');
  799. // グループの場合
  800. if (grant == GRANT_USER_GROUP) {
  801. debug('grant is usergroup', grantUserGroupId);
  802. return UserGroupRelation.findByGroupIdAndUser(grantUserGroupId, userData)
  803. .then((relation) => {
  804. if (relation == null) {
  805. return new Error('no relations were exist for group and user.');
  806. }
  807. return PageGroupRelation.findOrCreateRelationForPageAndGroup(page, relation.relatedGroup);
  808. })
  809. .catch((err) => {
  810. return new Error('No UserGroup is exists. userGroupId : ', grantUserGroupId);
  811. });
  812. }
  813. else {
  814. return PageGroupRelation.removeAllByPage(page);
  815. }
  816. };
  817. // Instance method でいいのでは
  818. pageSchema.statics.pushToGrantedUsers = function(page, userData) {
  819. return new Promise(function(resolve, reject) {
  820. if (!page.grantedUsers || !Array.isArray(page.grantedUsers)) {
  821. page.grantedUsers = [];
  822. }
  823. page.grantedUsers.push(userData);
  824. page.save(function(err, data) {
  825. if (err) {
  826. return reject(err);
  827. }
  828. return resolve(data);
  829. });
  830. });
  831. };
  832. pageSchema.statics.pushRevision = function(pageData, newRevision, user) {
  833. var isCreate = false;
  834. if (pageData.revision === undefined) {
  835. debug('pushRevision on Create');
  836. isCreate = true;
  837. }
  838. return new Promise(function(resolve, reject) {
  839. newRevision.save(function(err, newRevision) {
  840. if (err) {
  841. debug('Error on saving revision', err);
  842. return reject(err);
  843. }
  844. debug('Successfully saved new revision', newRevision);
  845. pageData.revision = newRevision;
  846. pageData.lastUpdateUser = user;
  847. pageData.updatedAt = Date.now();
  848. pageData.save(function(err, data) {
  849. if (err) {
  850. // todo: remove new revision?
  851. debug('Error on save page data (after push revision)', err);
  852. return reject(err);
  853. }
  854. resolve(data);
  855. if (!isCreate) {
  856. debug('pushRevision on Update');
  857. }
  858. });
  859. });
  860. });
  861. };
  862. pageSchema.statics.create = function(path, body, user, options) {
  863. var Page = this
  864. , Revision = crowi.model('Revision')
  865. , format = options.format || 'markdown'
  866. , grant = options.grant || GRANT_PUBLIC
  867. , redirectTo = options.redirectTo || null
  868. , grantUserGroupId = options.grantUserGroupId || null;
  869. // force public
  870. if (isPortalPath(path)) {
  871. grant = GRANT_PUBLIC;
  872. }
  873. let savedPage = undefined;
  874. return Page.findOne({path: path})
  875. .then(pageData => {
  876. if (pageData) {
  877. throw new Error('Cannot create new page to existed path');
  878. }
  879. var newPage = new Page();
  880. newPage.path = path;
  881. newPage.creator = user;
  882. newPage.lastUpdateUser = user;
  883. newPage.createdAt = Date.now();
  884. newPage.updatedAt = Date.now();
  885. newPage.redirectTo = redirectTo;
  886. newPage.grant = grant;
  887. newPage.status = STATUS_PUBLISHED;
  888. newPage.grantedUsers = [];
  889. newPage.grantedUsers.push(user);
  890. return newPage.save();
  891. })
  892. .then((newPage) => {
  893. savedPage = newPage;
  894. })
  895. .then(() => {
  896. const newRevision = Revision.prepareRevision(savedPage, body, user, {format: format});
  897. return Page.pushRevision(savedPage, newRevision, user);
  898. })
  899. .then(() => {
  900. return Page.updateGrantUserGroup(savedPage, grant, grantUserGroupId, user);
  901. })
  902. .then(() => {
  903. pageEvent.emit('create', savedPage, user);
  904. return savedPage;
  905. });
  906. };
  907. pageSchema.statics.updatePage = function(pageData, body, user, options) {
  908. var Page = this
  909. , Revision = crowi.model('Revision')
  910. , grant = options.grant || null
  911. , grantUserGroupId = options.grantUserGroupId || null
  912. ;
  913. // update existing page
  914. var newRevision = Revision.prepareRevision(pageData, body, user);
  915. let savedPage = undefined;
  916. return Page.pushRevision(pageData, newRevision, user)
  917. .then((revision) => {
  918. // fetch Page
  919. return Page.findPageByPath(revision.path).populate('revision');
  920. })
  921. .then((page) => {
  922. savedPage = page;
  923. })
  924. .then(() => {
  925. return Page.updateGrant(savedPage, grant, user, grantUserGroupId);
  926. })
  927. .then((data) => {
  928. debug('Page grant update:', data);
  929. pageEvent.emit('update', savedPage, user);
  930. return savedPage;
  931. });
  932. };
  933. pageSchema.statics.deletePage = function(pageData, user, options) {
  934. var Page = this
  935. , newPath = Page.getDeletedPageName(pageData.path)
  936. ;
  937. if (Page.isDeletableName(pageData.path)) {
  938. return Page.rename(pageData, newPath, user, {createRedirectPage: true})
  939. .then((updatedPageData) => {
  940. return Page.updatePageProperty(updatedPageData, {status: STATUS_DELETED, lastUpdateUser: user});
  941. })
  942. .then(() => {
  943. return pageData;
  944. });
  945. }
  946. else {
  947. return Promise.reject('Page is not deletable.');
  948. }
  949. };
  950. pageSchema.statics.deletePageRecursively = function(pageData, user, options) {
  951. var Page = this
  952. , path = pageData.path
  953. , options = options || {}
  954. ;
  955. return Page.generateQueryToListWithDescendants(path, user, options)
  956. .then(function(pages) {
  957. return Promise.all(pages.map(function(page) {
  958. return Page.deletePage(page, user, options);
  959. }));
  960. })
  961. .then(function(data) {
  962. return pageData;
  963. });
  964. };
  965. pageSchema.statics.revertDeletedPage = function(pageData, user, options) {
  966. var Page = this
  967. , newPath = Page.getRevertDeletedPageName(pageData.path)
  968. ;
  969. // 削除時、元ページの path には必ず redirectTo 付きで、ページが作成される。
  970. // そのため、そいつは削除してOK
  971. // が、redirectTo ではないページが存在している場合それは何かがおかしい。(データ補正が必要)
  972. return new Promise(function(resolve, reject) {
  973. Page.findPageByPath(newPath)
  974. .then(function(originPageData) {
  975. if (originPageData.redirectTo !== pageData.path) {
  976. throw new Error('The new page of to revert is exists and the redirect path of the page is not the deleted page.');
  977. }
  978. return Page.completelyDeletePage(originPageData);
  979. }).then(function(done) {
  980. return Page.updatePageProperty(pageData, {status: STATUS_PUBLISHED, lastUpdateUser: user});
  981. }).then(function(done) {
  982. pageData.status = STATUS_PUBLISHED;
  983. debug('Revert deleted the page, and rename again it', pageData, newPath);
  984. return Page.rename(pageData, newPath, user, {});
  985. }).then(function(done) {
  986. pageData.path = newPath;
  987. resolve(pageData);
  988. }).catch(reject);
  989. });
  990. };
  991. pageSchema.statics.revertDeletedPageRecursively = function(pageData, user, options) {
  992. var Page = this
  993. , path = pageData.path
  994. , options = options || { includeDeletedPage: true}
  995. ;
  996. return new Promise(function(resolve, reject) {
  997. Page
  998. .generateQueryToListWithDescendants(path, user, options)
  999. .exec()
  1000. .then(function(pages) {
  1001. Promise.all(pages.map(function(page) {
  1002. return Page.revertDeletedPage(page, user, options);
  1003. }))
  1004. .then(function(data) {
  1005. return resolve(data[0]);
  1006. });
  1007. });
  1008. });
  1009. };
  1010. /**
  1011. * This is danger.
  1012. */
  1013. pageSchema.statics.completelyDeletePage = function(pageData, user, options) {
  1014. // Delete Bookmarks, Attachments, Revisions, Pages and emit delete
  1015. var Bookmark = crowi.model('Bookmark')
  1016. , Attachment = crowi.model('Attachment')
  1017. , Comment = crowi.model('Comment')
  1018. , Revision = crowi.model('Revision')
  1019. , PageGroupRelation = crowi.model('PageGroupRelation')
  1020. , Page = this
  1021. , pageId = pageData._id
  1022. ;
  1023. debug('Completely delete', pageData.path);
  1024. return new Promise(function(resolve, reject) {
  1025. Bookmark.removeBookmarksByPageId(pageId)
  1026. .then(function(done) {
  1027. }).then(function(done) {
  1028. return Attachment.removeAttachmentsByPageId(pageId);
  1029. }).then(function(done) {
  1030. return Comment.removeCommentsByPageId(pageId);
  1031. }).then(function(done) {
  1032. return Revision.removeRevisionsByPath(pageData.path);
  1033. }).then(function(done) {
  1034. return Page.removePageById(pageId);
  1035. }).then(function(done) {
  1036. return Page.removeRedirectOriginPageByPath(pageData.path);
  1037. }).then(function(done) {
  1038. return PageGroupRelation.removeAllByPage(pageData);
  1039. }).then(function(done) {
  1040. pageEvent.emit('delete', pageData, user); // update as renamed page
  1041. resolve(pageData);
  1042. }).catch(reject);
  1043. });
  1044. };
  1045. pageSchema.statics.completelyDeletePageRecursively = function(pageData, user, options) {
  1046. // Delete Bookmarks, Attachments, Revisions, Pages and emit delete
  1047. var Page = this
  1048. , path = pageData.path
  1049. , options = options || { includeDeletedPage: true }
  1050. ;
  1051. return new Promise(function(resolve, reject) {
  1052. Page
  1053. .generateQueryToListWithDescendants(path, user, options)
  1054. .then(function(pages) {
  1055. Promise.all(pages.map(function(page) {
  1056. return Page.completelyDeletePage(page, user, options);
  1057. }))
  1058. .then(function(data) {
  1059. return resolve(data[0]);
  1060. });
  1061. });
  1062. });
  1063. };
  1064. pageSchema.statics.removePageById = function(pageId) {
  1065. var Page = this;
  1066. return new Promise(function(resolve, reject) {
  1067. Page.remove({_id: pageId}, function(err, done) {
  1068. debug('Remove phisiaclly, the page', pageId, err, done);
  1069. if (err) {
  1070. return reject(err);
  1071. }
  1072. resolve(done);
  1073. });
  1074. });
  1075. };
  1076. pageSchema.statics.removePageByPath = function(pagePath) {
  1077. var Page = this;
  1078. return Page.findPageByPath(pagePath)
  1079. .then(function(pageData) {
  1080. return Page.removePageById(pageData.id);
  1081. });
  1082. };
  1083. /**
  1084. * remove the page that is redirecting to specified `pagePath` recursively
  1085. * ex: when
  1086. * '/page1' redirects to '/page2' and
  1087. * '/page2' redirects to '/page3'
  1088. * and given '/page3',
  1089. * '/page1' and '/page2' will be removed
  1090. *
  1091. * @param {string} pagePath
  1092. */
  1093. pageSchema.statics.removeRedirectOriginPageByPath = function(pagePath) {
  1094. var Page = this;
  1095. return Page.findPageByRedirectTo(pagePath)
  1096. .then((redirectOriginPageData) => {
  1097. // remove
  1098. return Page.removePageById(redirectOriginPageData.id)
  1099. // remove recursive
  1100. .then(() => {
  1101. return Page.removeRedirectOriginPageByPath(redirectOriginPageData.path);
  1102. });
  1103. })
  1104. .catch((err) => {
  1105. // do nothing if origin page doesn't exist
  1106. return Promise.resolve();
  1107. });
  1108. };
  1109. pageSchema.statics.rename = function(pageData, newPagePath, user, options) {
  1110. var Page = this
  1111. , Revision = crowi.model('Revision')
  1112. , path = pageData.path
  1113. , createRedirectPage = options.createRedirectPage || 0
  1114. , moveUnderTrees = options.moveUnderTrees || 0;
  1115. return Page.updatePageProperty(pageData, {updatedAt: Date.now(), path: newPagePath, lastUpdateUser: user}) // pageData の path を変更
  1116. .then((data) => {
  1117. // reivisions の path を変更
  1118. return Revision.updateRevisionListByPath(path, {path: newPagePath}, {});
  1119. })
  1120. .then(function(data) {
  1121. pageData.path = newPagePath;
  1122. if (createRedirectPage) {
  1123. var body = 'redirect ' + newPagePath;
  1124. Page.create(path, body, user, {redirectTo: newPagePath});
  1125. }
  1126. pageEvent.emit('update', pageData, user); // update as renamed page
  1127. return pageData;
  1128. });
  1129. };
  1130. pageSchema.statics.renameRecursively = function(pageData, newPagePathPrefix, user, options) {
  1131. var Page = this
  1132. , path = pageData.path
  1133. , pathRegExp = new RegExp('^' + escapeStringRegexp(path), 'i');
  1134. return Page.generateQueryToListWithDescendants(path, user, options)
  1135. .then(function(pages) {
  1136. return Promise.all(pages.map(function(page) {
  1137. const newPagePath = page.path.replace(pathRegExp, newPagePathPrefix);
  1138. return Page.rename(page, newPagePath, user, options);
  1139. }));
  1140. })
  1141. .then(function() {
  1142. pageData.path = newPagePathPrefix;
  1143. return pageData;
  1144. });
  1145. };
  1146. pageSchema.statics.getHistories = function() {
  1147. // TODO
  1148. return;
  1149. };
  1150. /**
  1151. * return path that added slash to the end for specified path
  1152. */
  1153. pageSchema.statics.addSlashOfEnd = function(path) {
  1154. let returnPath = path;
  1155. if (!path.match(/\/$/)) {
  1156. returnPath += '/';
  1157. }
  1158. return returnPath;
  1159. };
  1160. pageSchema.statics.GRANT_PUBLIC = GRANT_PUBLIC;
  1161. pageSchema.statics.GRANT_RESTRICTED = GRANT_RESTRICTED;
  1162. pageSchema.statics.GRANT_SPECIFIED = GRANT_SPECIFIED;
  1163. pageSchema.statics.GRANT_OWNER = GRANT_OWNER;
  1164. pageSchema.statics.PAGE_GRANT_ERROR = PAGE_GRANT_ERROR;
  1165. return mongoose.model('Page', pageSchema);
  1166. };