33use Activity ;
44use BookStack \Repos \UserRepo ;
55use Illuminate \Http \Request ;
6- use Illuminate \Support \Facades \Auth ;
76use BookStack \Http \Requests ;
87use BookStack \Repos \BookRepo ;
98use BookStack \Repos \ChapterRepo ;
@@ -180,21 +179,31 @@ public function saveSort($bookSlug, Request $request)
180179 return redirect ($ book ->getUrl ());
181180 }
182181
183- $ sortedBooks = [];
184182 // Sort pages and chapters
183+ $ sortedBooks = [];
184+ $ updatedModels = collect ();
185185 $ sortMap = json_decode ($ request ->get ('sort-tree ' ));
186186 $ defaultBookId = $ book ->id ;
187- foreach ($ sortMap as $ index => $ bookChild ) {
188- $ id = $ bookChild ->id ;
187+
188+ // Loop through contents of provided map and update entities accordingly
189+ foreach ($ sortMap as $ bookChild ) {
190+ $ priority = $ bookChild ->sort ;
191+ $ id = intval ($ bookChild ->id );
189192 $ isPage = $ bookChild ->type == 'page ' ;
190- $ bookId = $ this ->bookRepo ->exists ($ bookChild ->book ) ? $ bookChild ->book : $ defaultBookId ;
193+ $ bookId = $ this ->bookRepo ->exists ($ bookChild ->book ) ? intval ($ bookChild ->book ) : $ defaultBookId ;
194+ $ chapterId = ($ isPage && $ bookChild ->parentChapter === false ) ? 0 : intval ($ bookChild ->parentChapter );
191195 $ model = $ isPage ? $ this ->pageRepo ->getById ($ id ) : $ this ->chapterRepo ->getById ($ id );
192- $ isPage ? $ this ->pageRepo ->changeBook ($ bookId , $ model ) : $ this ->chapterRepo ->changeBook ($ bookId , $ model );
193- $ model ->priority = $ index ;
194- if ($ isPage ) {
195- $ model ->chapter_id = ($ bookChild ->parentChapter === false ) ? 0 : $ bookChild ->parentChapter ;
196+
197+ // Update models only if there's a change in parent chain or ordering.
198+ if ($ model ->priority !== $ priority || $ model ->book_id !== $ bookId || ($ isPage && $ model ->chapter_id !== $ chapterId )) {
199+ $ isPage ? $ this ->pageRepo ->changeBook ($ bookId , $ model ) : $ this ->chapterRepo ->changeBook ($ bookId , $ model );
200+ $ model ->priority = $ priority ;
201+ if ($ isPage ) $ model ->chapter_id = $ chapterId ;
202+ $ model ->save ();
203+ $ updatedModels ->push ($ model );
196204 }
197- $ model ->save ();
205+
206+ // Store involved books to be sorted later
198207 if (!in_array ($ bookId , $ sortedBooks )) {
199208 $ sortedBooks [] = $ bookId ;
200209 }
@@ -203,10 +212,12 @@ public function saveSort($bookSlug, Request $request)
203212 // Add activity for books
204213 foreach ($ sortedBooks as $ bookId ) {
205214 $ updatedBook = $ this ->bookRepo ->getById ($ bookId );
206- $ this ->bookRepo ->updateBookPermissions ($ updatedBook );
207215 Activity::add ($ updatedBook , 'book_sort ' , $ updatedBook ->id );
208216 }
209217
218+ // Update permissions on changed models
219+ $ this ->bookRepo ->buildJointPermissions ($ updatedModels );
220+
210221 return redirect ($ book ->getUrl ());
211222 }
212223
0 commit comments