page.js 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329
  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. pageSchema.statics.getHistories = function() {
  1121. // TODO
  1122. return;
  1123. };
  1124. /**
  1125. * return path that added slash to the end for specified path
  1126. */
  1127. pageSchema.statics.addSlashOfEnd = function(path) {
  1128. let returnPath = path;
  1129. if (!path.match(/\/$/)) {
  1130. returnPath += '/';
  1131. }
  1132. return returnPath;
  1133. };
  1134. pageSchema.statics.GRANT_PUBLIC = GRANT_PUBLIC;
  1135. pageSchema.statics.GRANT_RESTRICTED = GRANT_RESTRICTED;
  1136. pageSchema.statics.GRANT_SPECIFIED = GRANT_SPECIFIED;
  1137. pageSchema.statics.GRANT_OWNER = GRANT_OWNER;
  1138. pageSchema.statics.PAGE_GRANT_ERROR = PAGE_GRANT_ERROR;
  1139. return mongoose.model('Page', pageSchema);
  1140. };