page.js 34 KB

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