page.js 34 KB

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