]> BookStack Code Mirror - bookstack/blob - resources/assets/js/controllers.js
Merge branch 'master' of git://github.com/Abijeet/BookStack into Abijeet-master
[bookstack] / resources / assets / js / controllers.js
1 "use strict";
2
3 const moment = require('moment');
4 require('moment/locale/en-gb');
5 const editorOptions = require("./pages/page-form");
6
7 moment.locale('en-gb');
8
9 module.exports = function (ngApp, events) {
10
11     ngApp.controller('ImageManagerController', ['$scope', '$attrs', '$http', '$timeout', 'imageManagerService',
12         function ($scope, $attrs, $http, $timeout, imageManagerService) {
13
14             $scope.images = [];
15             $scope.imageType = $attrs.imageType;
16             $scope.selectedImage = false;
17             $scope.dependantPages = false;
18             $scope.showing = false;
19             $scope.hasMore = false;
20             $scope.imageUpdateSuccess = false;
21             $scope.imageDeleteSuccess = false;
22             $scope.uploadedTo = $attrs.uploadedTo;
23             $scope.view = 'all';
24
25             $scope.searching = false;
26             $scope.searchTerm = '';
27
28             let page = 0;
29             let previousClickTime = 0;
30             let previousClickImage = 0;
31             let dataLoaded = false;
32             let callback = false;
33
34             let preSearchImages = [];
35             let preSearchHasMore = false;
36
37             /**
38              * Used by dropzone to get the endpoint to upload to.
39              * @returns {string}
40              */
41             $scope.getUploadUrl = function () {
42                 return window.baseUrl('/images/' + $scope.imageType + '/upload');
43             };
44
45             /**
46              * Cancel the current search operation.
47              */
48             function cancelSearch() {
49                 $scope.searching = false;
50                 $scope.searchTerm = '';
51                 $scope.images = preSearchImages;
52                 $scope.hasMore = preSearchHasMore;
53             }
54             $scope.cancelSearch = cancelSearch;
55
56
57             /**
58              * Runs on image upload, Adds an image to local list of images
59              * and shows a success message to the user.
60              * @param file
61              * @param data
62              */
63             $scope.uploadSuccess = function (file, data) {
64                 $scope.$apply(() => {
65                     $scope.images.unshift(data);
66                 });
67                 events.emit('success', trans('components.image_upload_success'));
68             };
69
70             /**
71              * Runs the callback and hides the image manager.
72              * @param returnData
73              */
74             function callbackAndHide(returnData) {
75                 if (callback) callback(returnData);
76                 $scope.hide();
77             }
78
79             /**
80              * Image select action. Checks if a double-click was fired.
81              * @param image
82              */
83             $scope.imageSelect = function (image) {
84                 let dblClickTime = 300;
85                 let currentTime = Date.now();
86                 let timeDiff = currentTime - previousClickTime;
87
88                 if (timeDiff < dblClickTime && image.id === previousClickImage) {
89                     // If double click
90                     callbackAndHide(image);
91                 } else {
92                     // If single
93                     $scope.selectedImage = image;
94                     $scope.dependantPages = false;
95                 }
96                 previousClickTime = currentTime;
97                 previousClickImage = image.id;
98             };
99
100             /**
101              * Action that runs when the 'Select image' button is clicked.
102              * Runs the callback and hides the image manager.
103              */
104             $scope.selectButtonClick = function () {
105                 callbackAndHide($scope.selectedImage);
106             };
107
108             /**
109              * Show the image manager.
110              * Takes a callback to execute later on.
111              * @param doneCallback
112              */
113             function show(doneCallback) {
114                 callback = doneCallback;
115                 $scope.showing = true;
116                 $('#image-manager').find('.overlay').css('display', 'flex').hide().fadeIn(240);
117                 // Get initial images if they have not yet been loaded in.
118                 if (!dataLoaded) {
119                     fetchData();
120                     dataLoaded = true;
121                 }
122             }
123
124             // Connects up the image manger so it can be used externally
125             // such as from TinyMCE.
126             imageManagerService.show = show;
127             imageManagerService.showExternal = function (doneCallback) {
128                 $scope.$apply(() => {
129                     show(doneCallback);
130                 });
131             };
132             window.ImageManager = imageManagerService;
133
134             /**
135              * Hide the image manager
136              */
137             $scope.hide = function () {
138                 $scope.showing = false;
139                 $('#image-manager').find('.overlay').fadeOut(240);
140             };
141
142             let baseUrl = window.baseUrl('/images/' + $scope.imageType + '/all/');
143
144             /**
145              * Fetch the list image data from the server.
146              */
147             function fetchData() {
148                 let url = baseUrl + page + '?';
149                 let components = {};
150                 if ($scope.uploadedTo) components['page_id'] = $scope.uploadedTo;
151                 if ($scope.searching) components['term'] = $scope.searchTerm;
152
153
154                 url += Object.keys(components).map((key) => {
155                     return key + '=' + encodeURIComponent(components[key]);
156                 }).join('&');
157
158                 $http.get(url).then((response) => {
159                     $scope.images = $scope.images.concat(response.data.images);
160                     $scope.hasMore = response.data.hasMore;
161                     page++;
162                 });
163             }
164             $scope.fetchData = fetchData;
165
166             /**
167              * Start a search operation
168              */
169             $scope.searchImages = function() {
170
171                 if ($scope.searchTerm === '') {
172                     cancelSearch();
173                     return;
174                 }
175
176                 if (!$scope.searching) {
177                     preSearchImages = $scope.images;
178                     preSearchHasMore = $scope.hasMore;
179                 }
180
181                 $scope.searching = true;
182                 $scope.images = [];
183                 $scope.hasMore = false;
184                 page = 0;
185                 baseUrl = window.baseUrl('/images/' + $scope.imageType + '/search/');
186                 fetchData();
187             };
188
189             /**
190              * Set the current image listing view.
191              * @param viewName
192              */
193             $scope.setView = function(viewName) {
194                 cancelSearch();
195                 $scope.images = [];
196                 $scope.hasMore = false;
197                 page = 0;
198                 $scope.view = viewName;
199                 baseUrl = window.baseUrl('/images/' + $scope.imageType  + '/' + viewName + '/');
200                 fetchData();
201             };
202
203             /**
204              * Save the details of an image.
205              * @param event
206              */
207             $scope.saveImageDetails = function (event) {
208                 event.preventDefault();
209                 let url = window.baseUrl('/images/update/' + $scope.selectedImage.id);
210                 $http.put(url, this.selectedImage).then(response => {
211                     events.emit('success', trans('components.image_update_success'));
212                 }, (response) => {
213                     if (response.status === 422) {
214                         let errors = response.data;
215                         let message = '';
216                         Object.keys(errors).forEach((key) => {
217                             message += errors[key].join('\n');
218                         });
219                         events.emit('error', message);
220                     } else if (response.status === 403) {
221                         events.emit('error', response.data.error);
222                     }
223                 });
224             };
225
226             /**
227              * Delete an image from system and notify of success.
228              * Checks if it should force delete when an image
229              * has dependant pages.
230              * @param event
231              */
232             $scope.deleteImage = function (event) {
233                 event.preventDefault();
234                 let force = $scope.dependantPages !== false;
235                 let url = window.baseUrl('/images/' + $scope.selectedImage.id);
236                 if (force) url += '?force=true';
237                 $http.delete(url).then((response) => {
238                     $scope.images.splice($scope.images.indexOf($scope.selectedImage), 1);
239                     $scope.selectedImage = false;
240                     events.emit('success', trans('components.image_delete_success'));
241                 }, (response) => {
242                     // Pages failure
243                     if (response.status === 400) {
244                         $scope.dependantPages = response.data;
245                     } else if (response.status === 403) {
246                         events.emit('error', response.data.error);
247                     }
248                 });
249             };
250
251             /**
252              * Simple date creator used to properly format dates.
253              * @param stringDate
254              * @returns {Date}
255              */
256             $scope.getDate = function (stringDate) {
257                 return new Date(stringDate);
258             };
259
260         }]);
261
262     ngApp.controller('PageEditController', ['$scope', '$http', '$attrs', '$interval', '$timeout', '$sce',
263         function ($scope, $http, $attrs, $interval, $timeout, $sce) {
264
265         $scope.editorOptions = editorOptions();
266         $scope.editContent = '';
267         $scope.draftText = '';
268         let pageId = Number($attrs.pageId);
269         let isEdit = pageId !== 0;
270         let autosaveFrequency = 30; // AutoSave interval in seconds.
271         let isMarkdown = $attrs.editorType === 'markdown';
272         $scope.draftsEnabled = $attrs.draftsEnabled === 'true';
273         $scope.isUpdateDraft = Number($attrs.pageUpdateDraft) === 1;
274         $scope.isNewPageDraft = Number($attrs.pageNewDraft) === 1;
275
276         // Set initial header draft text
277         if ($scope.isUpdateDraft || $scope.isNewPageDraft) {
278             $scope.draftText = trans('entities.pages_editing_draft');
279         } else {
280             $scope.draftText = trans('entities.pages_editing_page');
281         }
282
283         let autoSave = false;
284
285         let currentContent = {
286             title: false,
287             html: false
288         };
289
290         if (isEdit && $scope.draftsEnabled) {
291             setTimeout(() => {
292                 startAutoSave();
293             }, 1000);
294         }
295
296         // Actions specifically for the markdown editor
297         if (isMarkdown) {
298             $scope.displayContent = '';
299             // Editor change event
300             $scope.editorChange = function (content) {
301                 $scope.displayContent = $sce.trustAsHtml(content);
302             }
303         }
304
305         if (!isMarkdown) {
306             $scope.editorChange = function() {};
307         }
308
309         let lastSave = 0;
310
311         /**
312          * Start the AutoSave loop, Checks for content change
313          * before performing the costly AJAX request.
314          */
315         function startAutoSave() {
316             currentContent.title = $('#name').val();
317             currentContent.html = $scope.editContent;
318
319             autoSave = $interval(() => {
320                 // Return if manually saved recently to prevent bombarding the server
321                 if (Date.now() - lastSave < (1000*autosaveFrequency)/2) return;
322                 let newTitle = $('#name').val();
323                 let newHtml = $scope.editContent;
324
325                 if (newTitle !== currentContent.title || newHtml !== currentContent.html) {
326                     currentContent.html = newHtml;
327                     currentContent.title = newTitle;
328                     saveDraft();
329                 }
330
331             }, 1000 * autosaveFrequency);
332         }
333
334         let draftErroring = false;
335         /**
336          * Save a draft update into the system via an AJAX request.
337          */
338         function saveDraft() {
339             if (!$scope.draftsEnabled) return;
340             let data = {
341                 name: $('#name').val(),
342                 html: isMarkdown ? $sce.getTrustedHtml($scope.displayContent) : $scope.editContent
343             };
344
345             if (isMarkdown) data.markdown = $scope.editContent;
346
347             let url = window.baseUrl('/ajax/page/' + pageId + '/save-draft');
348             $http.put(url, data).then(responseData => {
349                 draftErroring = false;
350                 let updateTime = moment.utc(moment.unix(responseData.data.timestamp)).toDate();
351                 $scope.draftText = responseData.data.message + moment(updateTime).format('HH:mm');
352                 if (!$scope.isNewPageDraft) $scope.isUpdateDraft = true;
353                 showDraftSaveNotification();
354                 lastSave = Date.now();
355             }, errorRes => {
356                 if (draftErroring) return;
357                 events.emit('error', trans('errors.page_draft_autosave_fail'));
358                 draftErroring = true;
359             });
360         }
361
362         function showDraftSaveNotification() {
363             $scope.draftUpdated = true;
364             $timeout(() => {
365                 $scope.draftUpdated = false;
366             }, 2000)
367         }
368
369         $scope.forceDraftSave = function() {
370             saveDraft();
371         };
372
373         // Listen to save draft events from editor
374         $scope.$on('save-draft', saveDraft);
375
376         /**
377          * Discard the current draft and grab the current page
378          * content from the system via an AJAX request.
379          */
380         $scope.discardDraft = function () {
381             let url = window.baseUrl('/ajax/page/' + pageId);
382             $http.get(url).then(responseData => {
383                 if (autoSave) $interval.cancel(autoSave);
384                 $scope.draftText = trans('entities.pages_editing_page');
385                 $scope.isUpdateDraft = false;
386                 $scope.$broadcast('html-update', responseData.data.html);
387                 $scope.$broadcast('markdown-update', responseData.data.markdown || responseData.data.html);
388                 $('#name').val(responseData.data.name);
389                 $timeout(() => {
390                     startAutoSave();
391                 }, 1000);
392                 events.emit('success', trans('entities.pages_draft_discarded'));
393             });
394         };
395
396     }]);
397
398     ngApp.controller('PageTagController', ['$scope', '$http', '$attrs',
399         function ($scope, $http, $attrs) {
400
401             const pageId = Number($attrs.pageId);
402             $scope.tags = [];
403
404             $scope.sortOptions = {
405                 handle: '.handle',
406                 items: '> tr',
407                 containment: "parent",
408                 axis: "y"
409             };
410
411             /**
412              * Push an empty tag to the end of the scope tags.
413              */
414             function addEmptyTag() {
415                 $scope.tags.push({
416                     name: '',
417                     value: ''
418                 });
419             }
420             $scope.addEmptyTag = addEmptyTag;
421
422             /**
423              * Get all tags for the current book and add into scope.
424              */
425             function getTags() {
426                 let url = window.baseUrl(`/ajax/tags/get/page/${pageId}`);
427                 $http.get(url).then((responseData) => {
428                     $scope.tags = responseData.data;
429                     addEmptyTag();
430                 });
431             }
432             getTags();
433
434             /**
435              * Set the order property on all tags.
436              */
437             function setTagOrder() {
438                 for (let i = 0; i < $scope.tags.length; i++) {
439                     $scope.tags[i].order = i;
440                 }
441             }
442
443             /**
444              * When an tag changes check if another empty editable
445              * field needs to be added onto the end.
446              * @param tag
447              */
448             $scope.tagChange = function(tag) {
449                 let cPos = $scope.tags.indexOf(tag);
450                 if (cPos !== $scope.tags.length-1) return;
451
452                 if (tag.name !== '' || tag.value !== '') {
453                     addEmptyTag();
454                 }
455             };
456
457             /**
458              * When an tag field loses focus check the tag to see if its
459              * empty and therefore could be removed from the list.
460              * @param tag
461              */
462             $scope.tagBlur = function(tag) {
463                 let isLast = $scope.tags.length - 1 === $scope.tags.indexOf(tag);
464                 if (tag.name === '' && tag.value === '' && !isLast) {
465                     let cPos = $scope.tags.indexOf(tag);
466                     $scope.tags.splice(cPos, 1);
467                 }
468             };
469
470             /**
471              * Remove a tag from the current list.
472              * @param tag
473              */
474             $scope.removeTag = function(tag) {
475                 let cIndex = $scope.tags.indexOf(tag);
476                 $scope.tags.splice(cIndex, 1);
477             };
478
479         }]);
480
481
482     ngApp.controller('PageAttachmentController', ['$scope', '$http', '$attrs',
483         function ($scope, $http, $attrs) {
484
485             const pageId = $scope.uploadedTo = $attrs.pageId;
486             let currentOrder = '';
487             $scope.files = [];
488             $scope.editFile = false;
489             $scope.file = getCleanFile();
490             $scope.errors = {
491                 link: {},
492                 edit: {}
493             };
494
495             function getCleanFile() {
496                 return {
497                     page_id: pageId
498                 };
499             }
500
501             // Angular-UI-Sort options
502             $scope.sortOptions = {
503                 handle: '.handle',
504                 items: '> tr',
505                 containment: "parent",
506                 axis: "y",
507                 stop: sortUpdate,
508             };
509
510             /**
511              * Event listener for sort changes.
512              * Updates the file ordering on the server.
513              * @param event
514              * @param ui
515              */
516             function sortUpdate(event, ui) {
517                 let newOrder = $scope.files.map(file => {return file.id}).join(':');
518                 if (newOrder === currentOrder) return;
519
520                 currentOrder = newOrder;
521                 $http.put(window.baseUrl(`/attachments/sort/page/${pageId}`), {files: $scope.files}).then(resp => {
522                     events.emit('success', resp.data.message);
523                 }, checkError('sort'));
524             }
525
526             /**
527              * Used by dropzone to get the endpoint to upload to.
528              * @returns {string}
529              */
530             $scope.getUploadUrl = function (file) {
531                 let suffix = (typeof file !== 'undefined') ? `/${file.id}` : '';
532                 return window.baseUrl(`/attachments/upload${suffix}`);
533             };
534
535             /**
536              * Get files for the current page from the server.
537              */
538             function getFiles() {
539                 let url = window.baseUrl(`/attachments/get/page/${pageId}`);
540                 $http.get(url).then(resp => {
541                     $scope.files = resp.data;
542                     currentOrder = resp.data.map(file => {return file.id}).join(':');
543                 }, checkError('get'));
544             }
545             getFiles();
546
547             /**
548              * Runs on file upload, Adds an file to local file list
549              * and shows a success message to the user.
550              * @param file
551              * @param data
552              */
553             $scope.uploadSuccess = function (file, data) {
554                 $scope.$apply(() => {
555                     $scope.files.push(data);
556                 });
557                 events.emit('success', trans('entities.attachments_file_uploaded'));
558             };
559
560             /**
561              * Upload and overwrite an existing file.
562              * @param file
563              * @param data
564              */
565             $scope.uploadSuccessUpdate = function (file, data) {
566                 $scope.$apply(() => {
567                     let search = filesIndexOf(data);
568                     if (search !== -1) $scope.files[search] = data;
569
570                     if ($scope.editFile) {
571                         $scope.editFile = angular.copy(data);
572                         data.link = '';
573                     }
574                 });
575                 events.emit('success', trans('entities.attachments_file_updated'));
576             };
577
578             /**
579              * Delete a file from the server and, on success, the local listing.
580              * @param file
581              */
582             $scope.deleteFile = function(file) {
583                 if (!file.deleting) {
584                     file.deleting = true;
585                     return;
586                 }
587                   $http.delete(window.baseUrl(`/attachments/${file.id}`)).then(resp => {
588                       events.emit('success', resp.data.message);
589                       $scope.files.splice($scope.files.indexOf(file), 1);
590                   }, checkError('delete'));
591             };
592
593             /**
594              * Attach a link to a page.
595              * @param file
596              */
597             $scope.attachLinkSubmit = function(file) {
598                 file.uploaded_to = pageId;
599                 $http.post(window.baseUrl('/attachments/link'), file).then(resp => {
600                     $scope.files.push(resp.data);
601                     events.emit('success', trans('entities.attachments_link_attached'));
602                     $scope.file = getCleanFile();
603                 }, checkError('link'));
604             };
605
606             /**
607              * Start the edit mode for a file.
608              * @param file
609              */
610             $scope.startEdit = function(file) {
611                 $scope.editFile = angular.copy(file);
612                 $scope.editFile.link = (file.external) ? file.path : '';
613             };
614
615             /**
616              * Cancel edit mode
617              */
618             $scope.cancelEdit = function() {
619                 $scope.editFile = false;
620             };
621
622             /**
623              * Update the name and link of a file.
624              * @param file
625              */
626             $scope.updateFile = function(file) {
627                 $http.put(window.baseUrl(`/attachments/${file.id}`), file).then(resp => {
628                     let search = filesIndexOf(resp.data);
629                     if (search !== -1) $scope.files[search] = resp.data;
630
631                     if ($scope.editFile && !file.external) {
632                         $scope.editFile.link = '';
633                     }
634                     $scope.editFile = false;
635                     events.emit('success', trans('entities.attachments_updated_success'));
636                 }, checkError('edit'));
637             };
638
639             /**
640              * Get the url of a file.
641              */
642             $scope.getFileUrl = function(file) {
643                 return window.baseUrl('/attachments/' + file.id);
644             };
645
646             /**
647              * Search the local files via another file object.
648              * Used to search via object copies.
649              * @param file
650              * @returns int
651              */
652             function filesIndexOf(file) {
653                 for (let i = 0; i < $scope.files.length; i++) {
654                     if ($scope.files[i].id == file.id) return i;
655                 }
656                 return -1;
657             }
658
659             /**
660              * Check for an error response in a ajax request.
661              * @param errorGroupName
662              */
663             function checkError(errorGroupName) {
664                 $scope.errors[errorGroupName] = {};
665                 return function(response) {
666                     if (typeof response.data !== 'undefined' && typeof response.data.error !== 'undefined') {
667                         events.emit('error', response.data.error);
668                     }
669                     if (typeof response.data !== 'undefined' && typeof response.data.validation !== 'undefined') {
670                         $scope.errors[errorGroupName] = response.data.validation;
671                         console.log($scope.errors[errorGroupName])
672                     }
673                 }
674             }
675
676         }]);
677
678     // Controller used to reply to and add new comments
679     ngApp.controller('CommentReplyController', ['$scope', '$http', '$timeout', function ($scope, $http, $timeout) {
680         const MarkdownIt = require("markdown-it");
681         const md = new MarkdownIt({html: true});
682         let vm = this;
683
684         vm.saveComment = function () {
685             let pageId = $scope.comment.pageId || $scope.pageId;
686             let comment = $scope.comment.text;
687             if (!comment) {
688                 return events.emit('warning', trans('errors.empty_comment'));
689             }
690             let commentHTML = md.render($scope.comment.text);
691             let serviceUrl = `/ajax/page/${pageId}/comment/`;
692             let httpMethod = 'post';
693             let reqObj = {
694                 text: comment,
695                 html: commentHTML
696             };
697
698             if ($scope.isEdit === true) {
699                 // this will be set when editing the comment.
700                 serviceUrl = `/ajax/page/${pageId}/comment/${$scope.comment.id}`;
701                 httpMethod = 'put';
702             } else if ($scope.isReply === true) {
703                 // if its reply, get the parent comment id
704                 reqObj.parent_id = $scope.parentId;
705             }
706             $http[httpMethod](window.baseUrl(serviceUrl), reqObj).then(resp => {
707                 if (!isCommentOpSuccess(resp)) {
708                      return;
709                 }
710                 // hide the comments first, and then retrigger the refresh
711                 if ($scope.isEdit) {
712                     updateComment($scope.comment, resp.data);
713                     $scope.$emit('evt.comment-success', $scope.comment.id);
714                 } else {
715                     $scope.comment.text = '';
716                     if ($scope.isReply === true && $scope.parent.sub_comments) {
717                         $scope.parent.sub_comments.push(resp.data.comment);
718                     } else {
719                         $scope.$emit('evt.new-comment', resp.data.comment);
720                     }
721                     $scope.$emit('evt.comment-success', null, true);
722                 }
723                 $scope.comment.is_hidden = true;
724                 $timeout(function() {
725                     $scope.comment.is_hidden = false;
726                 });
727
728                 events.emit('success', trans(resp.data.message));
729
730             }, checkError);
731
732         };
733
734         function checkError(response) {
735             let msg = null;
736             if (isCommentOpSuccess(response)) {
737                 // all good
738                 return;
739             } else if (response.data) {
740                 msg = response.data.message;
741             } else {
742                 msg = trans('errors.comment_add');
743             }
744             if (msg) {
745                 events.emit('success', msg);
746             }
747         }
748     }]);
749
750     // Controller used to delete comments
751     ngApp.controller('CommentDeleteController', ['$scope', '$http', '$timeout', function ($scope, $http, $timeout) {
752         let vm = this;
753
754         vm.delete = function(comment) {
755             $http.delete(window.baseUrl(`/ajax/comment/${comment.id}`)).then(resp => {
756                 if (!isCommentOpSuccess(resp)) {
757                     return;
758                 }
759                 updateComment(comment, resp.data, $timeout, true);
760             }, function (resp) {
761                 if (isCommentOpSuccess(resp)) {
762                     events.emit('success', trans('entities.comment_deleted'));
763                 } else {
764                     events.emit('error', trans('error.comment_delete'));
765                 }
766             });
767         };
768     }]);
769
770     // Controller used to fetch all comments for a page
771     ngApp.controller('CommentListController', ['$scope', '$http', '$timeout', '$location', function ($scope, $http, $timeout, $location) {
772         let vm = this;
773         $scope.errors = {};
774         // keep track of comment levels
775         $scope.level = 1;
776         vm.totalCommentsStr = trans('entities.comments_loading');
777         vm.permissions = {};
778         vm.trans = window.trans;
779
780         $scope.$on('evt.new-comment', function (event, comment) {
781             // add the comment to the comment list.
782             vm.comments.push(comment);
783             ++vm.totalComments;
784             setTotalCommentMsg();
785             event.stopPropagation();
786             event.preventDefault();
787         });
788
789         vm.canEditDelete = function (comment, prop) {
790             if (!comment.active) {
791                 return false;
792             }
793             let propAll = prop + '_all';
794             let propOwn = prop + '_own';
795
796             if (vm.permissions[propAll]) {
797                 return true;
798             }
799
800             if (vm.permissions[propOwn] && comment.created_by.id === vm.current_user_id) {
801                 return true;
802             }
803
804             return false;
805         };
806
807         vm.canComment = function () {
808             return vm.permissions.comment_create;
809         };
810
811         // check if there are is any direct linking
812         let linkedCommentId = $location.search().cm;
813
814         $timeout(function() {
815             $http.get(window.baseUrl(`/ajax/page/${$scope.pageId}/comments/`)).then(resp => {
816                 if (!isCommentOpSuccess(resp)) {
817                     // just show that no comments are available.
818                     vm.totalComments = 0;
819                     setTotalCommentMsg();
820                     return;
821                 }
822                 vm.comments = resp.data.comments;
823                 vm.totalComments = +resp.data.total;
824                 vm.permissions = resp.data.permissions;
825                 vm.current_user_id = resp.data.user_id;
826                 setTotalCommentMsg();
827                 if (!linkedCommentId) {
828                     return;
829                 }
830                 $timeout(function() {
831                     // wait for the UI to render.
832                     focusLinkedComment(linkedCommentId);
833                 });
834             }, checkError);
835         });
836
837         function setTotalCommentMsg () {
838             if (vm.totalComments === 0) {
839                 vm.totalCommentsStr = trans('entities.no_comments');
840             } else if (vm.totalComments === 1) {
841                 vm.totalCommentsStr = trans('entities.one_comment');
842             } else {
843                 vm.totalCommentsStr = trans('entities.x_comments', {
844                     numComments: vm.totalComments
845                 });
846             }
847         }
848
849         function focusLinkedComment(linkedCommentId) {
850             let comment = angular.element('#' + linkedCommentId);
851             if (comment.length === 0) {
852                 return;
853             }
854
855             window.setupPageShow.goToText(linkedCommentId);
856         }
857
858         function checkError(response) {
859             let msg = null;
860             if (isCommentOpSuccess(response)) {
861                 // all good
862                 return;
863             } else if (response.data) {
864                 msg = response.data.message;
865             } else {
866                 msg = trans('errors.comment_list');
867             }
868             if (msg) {
869                 events.emit('success', msg);
870             }
871         }
872     }]);
873
874     function updateComment(comment, resp, $timeout, isDelete) {
875         comment.text = resp.comment.text;
876         comment.updated = resp.comment.updated;
877         comment.updated_by = resp.comment.updated_by;
878         comment.active = resp.comment.active;
879         if (isDelete && !resp.comment.active) {
880             comment.html = trans('entities.comment_deleted');
881         } else {
882             comment.html = resp.comment.html;
883         }
884         if (!$timeout) {
885             return;
886         }
887         comment.is_hidden = true;
888         $timeout(function() {
889             comment.is_hidden = false;
890         });
891     }
892
893     function isCommentOpSuccess(resp) {
894         if (resp && resp.data && resp.data.status === 'success') {
895             return true;
896         }
897         return false;
898     }
899 };