]> BookStack Code Mirror - bookstack/blob - resources/assets/js/controllers.js
Prevented guest users creating draft pages.
[bookstack] / resources / assets / js / controllers.js
1 "use strict";
2
3 const moment = require('moment');
4
5 module.exports = function (ngApp, events) {
6
7     ngApp.controller('ImageManagerController', ['$scope', '$attrs', '$http', '$timeout', 'imageManagerService',
8         function ($scope, $attrs, $http, $timeout, imageManagerService) {
9
10             $scope.images = [];
11             $scope.imageType = $attrs.imageType;
12             $scope.selectedImage = false;
13             $scope.dependantPages = false;
14             $scope.showing = false;
15             $scope.hasMore = false;
16             $scope.imageUpdateSuccess = false;
17             $scope.imageDeleteSuccess = false;
18             $scope.uploadedTo = $attrs.uploadedTo;
19             $scope.view = 'all';
20             
21             $scope.searching = false;
22             $scope.searchTerm = '';
23
24             var page = 0;
25             var previousClickTime = 0;
26             var previousClickImage = 0;
27             var dataLoaded = false;
28             var callback = false;
29
30             var preSearchImages = [];
31             var preSearchHasMore = false;
32
33             /**
34              * Used by dropzone to get the endpoint to upload to.
35              * @returns {string}
36              */
37             $scope.getUploadUrl = function () {
38                 return window.baseUrl('/images/' + $scope.imageType + '/upload');
39             };
40
41             /**
42              * Cancel the current search operation.
43              */
44             function cancelSearch() {
45                 $scope.searching = false;
46                 $scope.searchTerm = '';
47                 $scope.images = preSearchImages;
48                 $scope.hasMore = preSearchHasMore;
49             }
50             $scope.cancelSearch = cancelSearch;
51             
52
53             /**
54              * Runs on image upload, Adds an image to local list of images
55              * and shows a success message to the user.
56              * @param file
57              * @param data
58              */
59             $scope.uploadSuccess = function (file, data) {
60                 $scope.$apply(() => {
61                     $scope.images.unshift(data);
62                 });
63                 events.emit('success', 'Image uploaded');
64             };
65
66             /**
67              * Runs the callback and hides the image manager.
68              * @param returnData
69              */
70             function callbackAndHide(returnData) {
71                 if (callback) callback(returnData);
72                 $scope.hide();
73             }
74
75             /**
76              * Image select action. Checks if a double-click was fired.
77              * @param image
78              */
79             $scope.imageSelect = function (image) {
80                 var dblClickTime = 300;
81                 var currentTime = Date.now();
82                 var timeDiff = currentTime - previousClickTime;
83
84                 if (timeDiff < dblClickTime && image.id === previousClickImage) {
85                     // If double click
86                     callbackAndHide(image);
87                 } else {
88                     // If single
89                     $scope.selectedImage = image;
90                     $scope.dependantPages = false;
91                 }
92                 previousClickTime = currentTime;
93                 previousClickImage = image.id;
94             };
95
96             /**
97              * Action that runs when the 'Select image' button is clicked.
98              * Runs the callback and hides the image manager.
99              */
100             $scope.selectButtonClick = function () {
101                 callbackAndHide($scope.selectedImage);
102             };
103
104             /**
105              * Show the image manager.
106              * Takes a callback to execute later on.
107              * @param doneCallback
108              */
109             function show(doneCallback) {
110                 callback = doneCallback;
111                 $scope.showing = true;
112                 $('#image-manager').find('.overlay').css('display', 'flex').hide().fadeIn(240);
113                 // Get initial images if they have not yet been loaded in.
114                 if (!dataLoaded) {
115                     fetchData();
116                     dataLoaded = true;
117                 }
118             }
119
120             // Connects up the image manger so it can be used externally
121             // such as from TinyMCE.
122             imageManagerService.show = show;
123             imageManagerService.showExternal = function (doneCallback) {
124                 $scope.$apply(() => {
125                     show(doneCallback);
126                 });
127             };
128             window.ImageManager = imageManagerService;
129
130             /**
131              * Hide the image manager
132              */
133             $scope.hide = function () {
134                 $scope.showing = false;
135                 $('#image-manager').find('.overlay').fadeOut(240);
136             };
137
138             var baseUrl = window.baseUrl('/images/' + $scope.imageType + '/all/');
139
140             /**
141              * Fetch the list image data from the server.
142              */
143             function fetchData() {
144                 var url = baseUrl + page + '?';
145                 var components = {};
146                 if ($scope.uploadedTo) components['page_id'] = $scope.uploadedTo;
147                 if ($scope.searching) components['term'] = $scope.searchTerm;
148
149
150                 var urlQueryString = Object.keys(components).map((key) => {
151                     return key + '=' + encodeURIComponent(components[key]);
152                 }).join('&');
153                 url += urlQueryString;
154
155                 $http.get(url).then((response) => {
156                     $scope.images = $scope.images.concat(response.data.images);
157                     $scope.hasMore = response.data.hasMore;
158                     page++;
159                 });
160             }
161             $scope.fetchData = fetchData;
162
163             /**
164              * Start a search operation
165              * @param searchTerm
166              */
167             $scope.searchImages = function() {
168
169                 if ($scope.searchTerm === '') {
170                     cancelSearch();
171                     return;
172                 }
173
174                 if (!$scope.searching) {
175                     preSearchImages = $scope.images;
176                     preSearchHasMore = $scope.hasMore;
177                 }
178
179                 $scope.searching = true;
180                 $scope.images = [];
181                 $scope.hasMore = false;
182                 page = 0;
183                 baseUrl = window.baseUrl('/images/' + $scope.imageType + '/search/');
184                 fetchData();
185             };
186
187             /**
188              * Set the current image listing view.
189              * @param viewName
190              */
191             $scope.setView = function(viewName) {
192                 cancelSearch();
193                 $scope.images = [];
194                 $scope.hasMore = false;
195                 page = 0;
196                 $scope.view = viewName;
197                 baseUrl = window.baseUrl('/images/' + $scope.imageType  + '/' + viewName + '/');
198                 fetchData();
199             }
200
201             /**
202              * Save the details of an image.
203              * @param event
204              */
205             $scope.saveImageDetails = function (event) {
206                 event.preventDefault();
207                 var url = window.baseUrl('/images/update/' + $scope.selectedImage.id);
208                 $http.put(url, this.selectedImage).then((response) => {
209                     events.emit('success', 'Image details updated');
210                 }, (response) => {
211                     if (response.status === 422) {
212                         var errors = response.data;
213                         var message = '';
214                         Object.keys(errors).forEach((key) => {
215                             message += errors[key].join('\n');
216                         });
217                         events.emit('error', message);
218                     } else if (response.status === 403) {
219                         events.emit('error', response.data.error);
220                     }
221                 });
222             };
223
224             /**
225              * Delete an image from system and notify of success.
226              * Checks if it should force delete when an image
227              * has dependant pages.
228              * @param event
229              */
230             $scope.deleteImage = function (event) {
231                 event.preventDefault();
232                 var force = $scope.dependantPages !== false;
233                 var url = window.baseUrl('/images/' + $scope.selectedImage.id);
234                 if (force) url += '?force=true';
235                 $http.delete(url).then((response) => {
236                     $scope.images.splice($scope.images.indexOf($scope.selectedImage), 1);
237                     $scope.selectedImage = false;
238                     events.emit('success', 'Image successfully deleted');
239                 }, (response) => {
240                     // Pages failure
241                     if (response.status === 400) {
242                         $scope.dependantPages = response.data;
243                     } else if (response.status === 403) {
244                         events.emit('error', response.data.error);
245                     }
246                 });
247             };
248
249             /**
250              * Simple date creator used to properly format dates.
251              * @param stringDate
252              * @returns {Date}
253              */
254             $scope.getDate = function (stringDate) {
255                 return new Date(stringDate);
256             };
257
258         }]);
259
260
261     ngApp.controller('BookShowController', ['$scope', '$http', '$attrs', '$sce', function ($scope, $http, $attrs, $sce) {
262         $scope.searching = false;
263         $scope.searchTerm = '';
264         $scope.searchResults = '';
265
266         $scope.searchBook = function (e) {
267             e.preventDefault();
268             var term = $scope.searchTerm;
269             if (term.length == 0) return;
270             $scope.searching = true;
271             $scope.searchResults = '';
272             var searchUrl = window.baseUrl('/search/book/' + $attrs.bookId);
273             searchUrl += '?term=' + encodeURIComponent(term);
274             $http.get(searchUrl).then((response) => {
275                 $scope.searchResults = $sce.trustAsHtml(response.data);
276             });
277         };
278
279         $scope.checkSearchForm = function () {
280             if ($scope.searchTerm.length < 1) {
281                 $scope.searching = false;
282             }
283         };
284
285         $scope.clearSearch = function () {
286             $scope.searching = false;
287             $scope.searchTerm = '';
288         };
289
290     }]);
291
292
293     ngApp.controller('PageEditController', ['$scope', '$http', '$attrs', '$interval', '$timeout', '$sce',
294         function ($scope, $http, $attrs, $interval, $timeout, $sce) {
295
296         $scope.editorOptions = require('./pages/page-form');
297         $scope.editContent = '';
298         $scope.draftText = '';
299         var pageId = Number($attrs.pageId);
300         var isEdit = pageId !== 0;
301         var autosaveFrequency = 30; // AutoSave interval in seconds.
302         var isMarkdown = $attrs.editorType === 'markdown';
303         $scope.draftsEnabled = $attrs.draftsEnabled === 'true';
304         $scope.isUpdateDraft = Number($attrs.pageUpdateDraft) === 1;
305         $scope.isNewPageDraft = Number($attrs.pageNewDraft) === 1;
306
307         // Set inital header draft text
308         if ($scope.isUpdateDraft || $scope.isNewPageDraft) {
309             $scope.draftText = 'Editing Draft'
310         } else {
311             $scope.draftText = 'Editing Page'
312         };
313
314         var autoSave = false;
315
316         var currentContent = {
317             title: false,
318             html: false
319         };
320
321         if (isEdit && $scope.draftsEnabled) {
322             setTimeout(() => {
323                 startAutoSave();
324             }, 1000);
325         }
326
327         // Actions specifically for the markdown editor
328         if (isMarkdown) {
329             $scope.displayContent = '';
330             // Editor change event
331             $scope.editorChange = function (content) {
332                 $scope.displayContent = $sce.trustAsHtml(content);
333             }
334         }
335
336         if (!isMarkdown) {
337             $scope.editorChange = function() {};
338         }
339
340         let lastSave = 0;
341
342         /**
343          * Start the AutoSave loop, Checks for content change
344          * before performing the costly AJAX request.
345          */
346         function startAutoSave() {
347             currentContent.title = $('#name').val();
348             currentContent.html = $scope.editContent;
349
350             autoSave = $interval(() => {
351                 // Return if manually saved recently to prevent bombarding the server
352                 if (Date.now() - lastSave < (1000*autosaveFrequency)/2) return;
353                 var newTitle = $('#name').val();
354                 var newHtml = $scope.editContent;
355
356                 if (newTitle !== currentContent.title || newHtml !== currentContent.html) {
357                     currentContent.html = newHtml;
358                     currentContent.title = newTitle;
359                     saveDraft();
360                 }
361
362             }, 1000 * autosaveFrequency);
363         }
364
365         let draftErroring = false;
366         /**
367          * Save a draft update into the system via an AJAX request.
368          */
369         function saveDraft() {
370             if (!$scope.draftsEnabled) return;
371             var data = {
372                 name: $('#name').val(),
373                 html: isMarkdown ? $sce.getTrustedHtml($scope.displayContent) : $scope.editContent
374             };
375
376             if (isMarkdown) data.markdown = $scope.editContent;
377
378             let url = window.baseUrl('/ajax/page/' + pageId + '/save-draft');
379             $http.put(url, data).then(responseData => {
380                 draftErroring = false;
381                 var updateTime = moment.utc(moment.unix(responseData.data.timestamp)).toDate();
382                 $scope.draftText = responseData.data.message + moment(updateTime).format('HH:mm');
383                 if (!$scope.isNewPageDraft) $scope.isUpdateDraft = true;
384                 showDraftSaveNotification();
385                 lastSave = Date.now();
386             }, errorRes => {
387                 if (draftErroring) return;
388                 events.emit('error', 'Failed to save draft. Ensure you have internet connection before saving this page.')
389                 draftErroring = true;
390             });
391         }
392
393         function showDraftSaveNotification() {
394             $scope.draftUpdated = true;
395             $timeout(() => {
396                 $scope.draftUpdated = false;
397             }, 2000)
398         }
399
400         $scope.forceDraftSave = function() {
401             saveDraft();
402         };
403
404         // Listen to shortcuts coming via events
405         $scope.$on('editor-keydown', (event, data) => {
406             // Save shortcut (ctrl+s)
407             if (data.keyCode == 83 && (navigator.platform.match("Mac") ? data.metaKey : data.ctrlKey)) {
408                 data.preventDefault();
409                 saveDraft();
410             }
411         });
412
413         /**
414          * Discard the current draft and grab the current page
415          * content from the system via an AJAX request.
416          */
417         $scope.discardDraft = function () {
418             let url = window.baseUrl('/ajax/page/' + pageId);
419             $http.get(url).then((responseData) => {
420                 if (autoSave) $interval.cancel(autoSave);
421                 $scope.draftText = 'Editing Page';
422                 $scope.isUpdateDraft = false;
423                 $scope.$broadcast('html-update', responseData.data.html);
424                 $scope.$broadcast('markdown-update', responseData.data.markdown || responseData.data.html);
425                 $('#name').val(responseData.data.name);
426                 $timeout(() => {
427                     startAutoSave();
428                 }, 1000);
429                 events.emit('success', 'Draft discarded, The editor has been updated with the current page content');
430             });
431         };
432
433     }]);
434
435     ngApp.controller('PageTagController', ['$scope', '$http', '$attrs',
436         function ($scope, $http, $attrs) {
437
438             const pageId = Number($attrs.pageId);
439             $scope.tags = [];
440             
441             $scope.sortOptions = {
442                 handle: '.handle',
443                 items: '> tr',
444                 containment: "parent",
445                 axis: "y"
446             };
447
448             /**
449              * Push an empty tag to the end of the scope tags.
450              */
451             function addEmptyTag() {
452                 $scope.tags.push({
453                     name: '',
454                     value: ''
455                 });
456             }
457             $scope.addEmptyTag = addEmptyTag;
458
459             /**
460              * Get all tags for the current book and add into scope.
461              */
462             function getTags() {
463                 let url = window.baseUrl('/ajax/tags/get/page/' + pageId);
464                 $http.get(url).then((responseData) => {
465                     $scope.tags = responseData.data;
466                     addEmptyTag();
467                 });
468             }
469             getTags();
470
471             /**
472              * Set the order property on all tags.
473              */
474             function setTagOrder() {
475                 for (let i = 0; i < $scope.tags.length; i++) {
476                     $scope.tags[i].order = i;
477                 }
478             }
479
480             /**
481              * When an tag changes check if another empty editable
482              * field needs to be added onto the end.
483              * @param tag
484              */
485             $scope.tagChange = function(tag) {
486                 let cPos = $scope.tags.indexOf(tag);
487                 if (cPos !== $scope.tags.length-1) return;
488
489                 if (tag.name !== '' || tag.value !== '') {
490                     addEmptyTag();
491                 }
492             };
493
494             /**
495              * When an tag field loses focus check the tag to see if its
496              * empty and therefore could be removed from the list.
497              * @param tag
498              */
499             $scope.tagBlur = function(tag) {
500                 let isLast = $scope.tags.length - 1 === $scope.tags.indexOf(tag);
501                 if (tag.name === '' && tag.value === '' && !isLast) {
502                     let cPos = $scope.tags.indexOf(tag);
503                     $scope.tags.splice(cPos, 1);
504                 }
505             };
506
507             /**
508              * Save the tags to the current page.
509              */
510             $scope.saveTags = function() {
511                 setTagOrder();
512                 let postData = {tags: $scope.tags};
513                 let url = window.baseUrl('/ajax/tags/update/page/' + pageId);
514                 $http.post(url, postData).then((responseData) => {
515                     $scope.tags = responseData.data.tags;
516                     addEmptyTag();
517                     events.emit('success', responseData.data.message);
518                 })
519             };
520
521             /**
522              * Remove a tag from the current list.
523              * @param tag
524              */
525             $scope.removeTag = function(tag) {
526                 let cIndex = $scope.tags.indexOf(tag);
527                 $scope.tags.splice(cIndex, 1);
528             };
529
530         }]);
531
532 };
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549