Dan Brown

Merge pull request #110 from ssddanbrown/page_attributes

Attribute System. Closes #48.
1 language: php 1 language: php
2 -
3 php: 2 php:
4 - 7.0 3 - 7.0
5 4
6 cache: 5 cache:
7 directories: 6 directories:
8 - - node_modules
9 - vendor 7 - vendor
10 8
11 addons: 9 addons:
......
1 <?php namespace BookStack; 1 <?php namespace BookStack;
2 2
3 3
4 -abstract class Entity extends Ownable 4 +class Entity extends Ownable
5 { 5 {
6 6
7 /** 7 /**
...@@ -55,6 +55,15 @@ abstract class Entity extends Ownable ...@@ -55,6 +55,15 @@ abstract class Entity extends Ownable
55 } 55 }
56 56
57 /** 57 /**
58 + * Get the Tag models that have been user assigned to this entity.
59 + * @return \Illuminate\Database\Eloquent\Relations\MorphMany
60 + */
61 + public function tags()
62 + {
63 + return $this->morphMany(Tag::class, 'entity')->orderBy('order', 'asc');
64 + }
65 +
66 + /**
58 * Get this entities restrictions. 67 * Get this entities restrictions.
59 */ 68 */
60 public function permissions() 69 public function permissions()
...@@ -115,6 +124,22 @@ abstract class Entity extends Ownable ...@@ -115,6 +124,22 @@ abstract class Entity extends Ownable
115 } 124 }
116 125
117 /** 126 /**
127 + * Get an instance of an entity of the given type.
128 + * @param $type
129 + * @return Entity
130 + */
131 + public static function getEntityInstance($type)
132 + {
133 + $types = ['Page', 'Book', 'Chapter'];
134 + $className = str_replace([' ', '-', '_'], '', ucwords($type));
135 + if (!in_array($className, $types)) {
136 + return null;
137 + }
138 +
139 + return app('BookStack\\' . $className);
140 + }
141 +
142 + /**
118 * Gets a limited-length version of the entities name. 143 * Gets a limited-length version of the entities name.
119 * @param int $length 144 * @param int $length
120 * @return string 145 * @return string
...@@ -132,54 +157,54 @@ abstract class Entity extends Ownable ...@@ -132,54 +157,54 @@ abstract class Entity extends Ownable
132 * @param string[] array $wheres 157 * @param string[] array $wheres
133 * @return mixed 158 * @return mixed
134 */ 159 */
135 - public static function fullTextSearchQuery($fieldsToSearch, $terms, $wheres = []) 160 + public function fullTextSearchQuery($fieldsToSearch, $terms, $wheres = [])
136 { 161 {
137 $exactTerms = []; 162 $exactTerms = [];
138 - foreach ($terms as $key => $term) { 163 + if (count($terms) === 0) {
139 - $term = htmlentities($term, ENT_QUOTES); 164 + $search = $this;
140 - $term = preg_replace('/[+\-><\(\)~*\"@]+/', ' ', $term); 165 + $orderBy = 'updated_at';
141 - if (preg_match('/\s/', $term)) { 166 + } else {
142 - $exactTerms[] = '%' . $term . '%'; 167 + foreach ($terms as $key => $term) {
143 - $term = '"' . $term . '"'; 168 + $term = htmlentities($term, ENT_QUOTES);
144 - } else { 169 + $term = preg_replace('/[+\-><\(\)~*\"@]+/', ' ', $term);
145 - $term = '' . $term . '*'; 170 + if (preg_match('/\s/', $term)) {
171 + $exactTerms[] = '%' . $term . '%';
172 + $term = '"' . $term . '"';
173 + } else {
174 + $term = '' . $term . '*';
175 + }
176 + if ($term !== '*') $terms[$key] = $term;
146 } 177 }
147 - if ($term !== '*') $terms[$key] = $term; 178 + $termString = implode(' ', $terms);
148 - } 179 + $fields = implode(',', $fieldsToSearch);
149 - $termString = implode(' ', $terms); 180 + $search = static::selectRaw('*, MATCH(name) AGAINST(? IN BOOLEAN MODE) AS title_relevance', [$termString]);
150 - $fields = implode(',', $fieldsToSearch); 181 + $search = $search->whereRaw('MATCH(' . $fields . ') AGAINST(? IN BOOLEAN MODE)', [$termString]);
151 - $search = static::selectRaw('*, MATCH(name) AGAINST(? IN BOOLEAN MODE) AS title_relevance', [$termString]); 182 +
152 - $search = $search->whereRaw('MATCH(' . $fields . ') AGAINST(? IN BOOLEAN MODE)', [$termString]); 183 + // Ensure at least one exact term matches if in search
153 - 184 + if (count($exactTerms) > 0) {
154 - // Ensure at least one exact term matches if in search 185 + $search = $search->where(function ($query) use ($exactTerms, $fieldsToSearch) {
155 - if (count($exactTerms) > 0) { 186 + foreach ($exactTerms as $exactTerm) {
156 - $search = $search->where(function ($query) use ($exactTerms, $fieldsToSearch) { 187 + foreach ($fieldsToSearch as $field) {
157 - foreach ($exactTerms as $exactTerm) { 188 + $query->orWhere($field, 'like', $exactTerm);
158 - foreach ($fieldsToSearch as $field) { 189 + }
159 - $query->orWhere($field, 'like', $exactTerm);
160 } 190 }
161 - } 191 + });
162 - }); 192 + }
163 - } 193 + $orderBy = 'title_relevance';
194 + };
164 195
165 // Add additional where terms 196 // Add additional where terms
166 foreach ($wheres as $whereTerm) { 197 foreach ($wheres as $whereTerm) {
167 $search->where($whereTerm[0], $whereTerm[1], $whereTerm[2]); 198 $search->where($whereTerm[0], $whereTerm[1], $whereTerm[2]);
168 } 199 }
169 // Load in relations 200 // Load in relations
170 - if (static::isA('page')) { 201 + if ($this->isA('page')) {
171 $search = $search->with('book', 'chapter', 'createdBy', 'updatedBy'); 202 $search = $search->with('book', 'chapter', 'createdBy', 'updatedBy');
172 - } else if (static::isA('chapter')) { 203 + } else if ($this->isA('chapter')) {
173 $search = $search->with('book'); 204 $search = $search->with('book');
174 } 205 }
175 206
176 - return $search->orderBy('title_relevance', 'desc'); 207 + return $search->orderBy($orderBy, 'desc');
177 } 208 }
178 - 209 +
179 - /**
180 - * Get the url for this item.
181 - * @return string
182 - */
183 - abstract public function getUrl();
184 -
185 } 210 }
......
...@@ -110,4 +110,15 @@ abstract class Controller extends BaseController ...@@ -110,4 +110,15 @@ abstract class Controller extends BaseController
110 return true; 110 return true;
111 } 111 }
112 112
113 + /**
114 + * Send back a json error message.
115 + * @param string $messageText
116 + * @param int $statusCode
117 + * @return mixed
118 + */
119 + protected function jsonError($messageText = "", $statusCode = 500)
120 + {
121 + return response()->json(['message' => $messageText], $statusCode);
122 + }
123 +
113 } 124 }
......
...@@ -72,7 +72,7 @@ class PageController extends Controller ...@@ -72,7 +72,7 @@ class PageController extends Controller
72 $this->checkOwnablePermission('page-create', $book); 72 $this->checkOwnablePermission('page-create', $book);
73 $this->setPageTitle('Edit Page Draft'); 73 $this->setPageTitle('Edit Page Draft');
74 74
75 - return view('pages/create', ['draft' => $draft, 'book' => $book]); 75 + return view('pages/edit', ['page' => $draft, 'book' => $book, 'isDraft' => true]);
76 } 76 }
77 77
78 /** 78 /**
......
1 +<?php namespace BookStack\Http\Controllers;
2 +
3 +use BookStack\Repos\TagRepo;
4 +use Illuminate\Http\Request;
5 +use BookStack\Http\Requests;
6 +
7 +class TagController extends Controller
8 +{
9 +
10 + protected $tagRepo;
11 +
12 + /**
13 + * TagController constructor.
14 + * @param $tagRepo
15 + */
16 + public function __construct(TagRepo $tagRepo)
17 + {
18 + $this->tagRepo = $tagRepo;
19 + }
20 +
21 + /**
22 + * Get all the Tags for a particular entity
23 + * @param $entityType
24 + * @param $entityId
25 + */
26 + public function getForEntity($entityType, $entityId)
27 + {
28 + $tags = $this->tagRepo->getForEntity($entityType, $entityId);
29 + return response()->json($tags);
30 + }
31 +
32 + /**
33 + * Update the tags for a particular entity.
34 + * @param $entityType
35 + * @param $entityId
36 + * @param Request $request
37 + * @return mixed
38 + */
39 + public function updateForEntity($entityType, $entityId, Request $request)
40 + {
41 + $entity = $this->tagRepo->getEntity($entityType, $entityId, 'update');
42 + if ($entity === null) return $this->jsonError("Entity not found", 404);
43 +
44 + $inputTags = $request->input('tags');
45 + $tags = $this->tagRepo->saveTagsToEntity($entity, $inputTags);
46 + return response()->json([
47 + 'tags' => $tags,
48 + 'message' => 'Tags successfully updated'
49 + ]);
50 + }
51 +
52 + /**
53 + * Get tag name suggestions from a given search term.
54 + * @param Request $request
55 + */
56 + public function getNameSuggestions(Request $request)
57 + {
58 + $searchTerm = $request->get('search');
59 + $suggestions = $this->tagRepo->getNameSuggestions($searchTerm);
60 + return response()->json($suggestions);
61 + }
62 +
63 + /**
64 + * Get tag value suggestions from a given search term.
65 + * @param Request $request
66 + */
67 + public function getValueSuggestions(Request $request)
68 + {
69 + $searchTerm = $request->get('search');
70 + $suggestions = $this->tagRepo->getValueSuggestions($searchTerm);
71 + return response()->json($suggestions);
72 + }
73 +
74 +}
...@@ -28,7 +28,7 @@ Route::group(['middleware' => 'auth'], function () { ...@@ -28,7 +28,7 @@ Route::group(['middleware' => 'auth'], function () {
28 // Pages 28 // Pages
29 Route::get('/{bookSlug}/page/create', 'PageController@create'); 29 Route::get('/{bookSlug}/page/create', 'PageController@create');
30 Route::get('/{bookSlug}/draft/{pageId}', 'PageController@editDraft'); 30 Route::get('/{bookSlug}/draft/{pageId}', 'PageController@editDraft');
31 - Route::post('/{bookSlug}/page/{pageId}', 'PageController@store'); 31 + Route::post('/{bookSlug}/draft/{pageId}', 'PageController@store');
32 Route::get('/{bookSlug}/page/{pageSlug}', 'PageController@show'); 32 Route::get('/{bookSlug}/page/{pageSlug}', 'PageController@show');
33 Route::get('/{bookSlug}/page/{pageSlug}/export/pdf', 'PageController@exportPdf'); 33 Route::get('/{bookSlug}/page/{pageSlug}/export/pdf', 'PageController@exportPdf');
34 Route::get('/{bookSlug}/page/{pageSlug}/export/html', 'PageController@exportHtml'); 34 Route::get('/{bookSlug}/page/{pageSlug}/export/html', 'PageController@exportHtml');
...@@ -80,11 +80,19 @@ Route::group(['middleware' => 'auth'], function () { ...@@ -80,11 +80,19 @@ Route::group(['middleware' => 'auth'], function () {
80 Route::delete('/{imageId}', 'ImageController@destroy'); 80 Route::delete('/{imageId}', 'ImageController@destroy');
81 }); 81 });
82 82
83 - // Ajax routes 83 + // AJAX routes
84 Route::put('/ajax/page/{id}/save-draft', 'PageController@saveDraft'); 84 Route::put('/ajax/page/{id}/save-draft', 'PageController@saveDraft');
85 Route::get('/ajax/page/{id}', 'PageController@getPageAjax'); 85 Route::get('/ajax/page/{id}', 'PageController@getPageAjax');
86 Route::delete('/ajax/page/{id}', 'PageController@ajaxDestroy'); 86 Route::delete('/ajax/page/{id}', 'PageController@ajaxDestroy');
87 87
88 + // Tag routes (AJAX)
89 + Route::group(['prefix' => 'ajax/tags'], function() {
90 + Route::get('/get/{entityType}/{entityId}', 'TagController@getForEntity');
91 + Route::get('/suggest/names', 'TagController@getNameSuggestions');
92 + Route::get('/suggest/values', 'TagController@getValueSuggestions');
93 + Route::post('/update/{entityType}/{entityId}', 'TagController@updateForEntity');
94 + });
95 +
88 // Links 96 // Links
89 Route::get('/link/{id}', 'PageController@redirectFromLink'); 97 Route::get('/link/{id}', 'PageController@redirectFromLink');
90 98
......
...@@ -286,8 +286,9 @@ class BookRepo extends EntityRepo ...@@ -286,8 +286,9 @@ class BookRepo extends EntityRepo
286 public function getBySearch($term, $count = 20, $paginationAppends = []) 286 public function getBySearch($term, $count = 20, $paginationAppends = [])
287 { 287 {
288 $terms = $this->prepareSearchTerms($term); 288 $terms = $this->prepareSearchTerms($term);
289 - $books = $this->permissionService->enforceBookRestrictions($this->book->fullTextSearchQuery(['name', 'description'], $terms)) 289 + $bookQuery = $this->permissionService->enforceBookRestrictions($this->book->fullTextSearchQuery(['name', 'description'], $terms));
290 - ->paginate($count)->appends($paginationAppends); 290 + $bookQuery = $this->addAdvancedSearchQueries($bookQuery, $term);
291 + $books = $bookQuery->paginate($count)->appends($paginationAppends);
291 $words = join('|', explode(' ', preg_quote(trim($term), '/'))); 292 $words = join('|', explode(' ', preg_quote(trim($term), '/')));
292 foreach ($books as $book) { 293 foreach ($books as $book) {
293 //highlight 294 //highlight
......
...@@ -168,8 +168,9 @@ class ChapterRepo extends EntityRepo ...@@ -168,8 +168,9 @@ class ChapterRepo extends EntityRepo
168 public function getBySearch($term, $whereTerms = [], $count = 20, $paginationAppends = []) 168 public function getBySearch($term, $whereTerms = [], $count = 20, $paginationAppends = [])
169 { 169 {
170 $terms = $this->prepareSearchTerms($term); 170 $terms = $this->prepareSearchTerms($term);
171 - $chapters = $this->permissionService->enforceChapterRestrictions($this->chapter->fullTextSearchQuery(['name', 'description'], $terms, $whereTerms)) 171 + $chapterQuery = $this->permissionService->enforceChapterRestrictions($this->chapter->fullTextSearchQuery(['name', 'description'], $terms, $whereTerms));
172 - ->paginate($count)->appends($paginationAppends); 172 + $chapterQuery = $this->addAdvancedSearchQueries($chapterQuery, $term);
173 + $chapters = $chapterQuery->paginate($count)->appends($paginationAppends);
173 $words = join('|', explode(' ', preg_quote(trim($term), '/'))); 174 $words = join('|', explode(' ', preg_quote(trim($term), '/')));
174 foreach ($chapters as $chapter) { 175 foreach ($chapters as $chapter) {
175 //highlight 176 //highlight
......
...@@ -6,6 +6,7 @@ use BookStack\Entity; ...@@ -6,6 +6,7 @@ use BookStack\Entity;
6 use BookStack\Page; 6 use BookStack\Page;
7 use BookStack\Services\PermissionService; 7 use BookStack\Services\PermissionService;
8 use BookStack\User; 8 use BookStack\User;
9 +use Illuminate\Support\Facades\Log;
9 10
10 class EntityRepo 11 class EntityRepo
11 { 12 {
...@@ -31,6 +32,12 @@ class EntityRepo ...@@ -31,6 +32,12 @@ class EntityRepo
31 protected $permissionService; 32 protected $permissionService;
32 33
33 /** 34 /**
35 + * Acceptable operators to be used in a query
36 + * @var array
37 + */
38 + protected $queryOperators = ['<=', '>=', '=', '<', '>', 'like', '!='];
39 +
40 + /**
34 * EntityService constructor. 41 * EntityService constructor.
35 */ 42 */
36 public function __construct() 43 public function __construct()
...@@ -163,6 +170,7 @@ class EntityRepo ...@@ -163,6 +170,7 @@ class EntityRepo
163 */ 170 */
164 protected function prepareSearchTerms($termString) 171 protected function prepareSearchTerms($termString)
165 { 172 {
173 + $termString = $this->cleanSearchTermString($termString);
166 preg_match_all('/"(.*?)"/', $termString, $matches); 174 preg_match_all('/"(.*?)"/', $termString, $matches);
167 if (count($matches[1]) > 0) { 175 if (count($matches[1]) > 0) {
168 $terms = $matches[1]; 176 $terms = $matches[1];
...@@ -174,5 +182,93 @@ class EntityRepo ...@@ -174,5 +182,93 @@ class EntityRepo
174 return $terms; 182 return $terms;
175 } 183 }
176 184
185 + /**
186 + * Removes any special search notation that should not
187 + * be used in a full-text search.
188 + * @param $termString
189 + * @return mixed
190 + */
191 + protected function cleanSearchTermString($termString)
192 + {
193 + // Strip tag searches
194 + $termString = preg_replace('/\[.*?\]/', '', $termString);
195 + // Reduced multiple spacing into single spacing
196 + $termString = preg_replace("/\s{2,}/", " ", $termString);
197 + return $termString;
198 + }
199 +
200 + /**
201 + * Get the available query operators as a regex escaped list.
202 + * @return mixed
203 + */
204 + protected function getRegexEscapedOperators()
205 + {
206 + $escapedOperators = [];
207 + foreach ($this->queryOperators as $operator) {
208 + $escapedOperators[] = preg_quote($operator);
209 + }
210 + return join('|', $escapedOperators);
211 + }
212 +
213 + /**
214 + * Parses advanced search notations and adds them to the db query.
215 + * @param $query
216 + * @param $termString
217 + * @return mixed
218 + */
219 + protected function addAdvancedSearchQueries($query, $termString)
220 + {
221 + $escapedOperators = $this->getRegexEscapedOperators();
222 + // Look for tag searches
223 + preg_match_all("/\[(.*?)((${escapedOperators})(.*?))?\]/", $termString, $tags);
224 + if (count($tags[0]) > 0) {
225 + $this->applyTagSearches($query, $tags);
226 + }
227 +
228 + return $query;
229 + }
230 +
231 + /**
232 + * Apply extracted tag search terms onto a entity query.
233 + * @param $query
234 + * @param $tags
235 + * @return mixed
236 + */
237 + protected function applyTagSearches($query, $tags) {
238 + $query->where(function($query) use ($tags) {
239 + foreach ($tags[1] as $index => $tagName) {
240 + $query->whereHas('tags', function($query) use ($tags, $index, $tagName) {
241 + $tagOperator = $tags[3][$index];
242 + $tagValue = $tags[4][$index];
243 + if (!empty($tagOperator) && !empty($tagValue) && in_array($tagOperator, $this->queryOperators)) {
244 + if (is_numeric($tagValue) && $tagOperator !== 'like') {
245 + // We have to do a raw sql query for this since otherwise PDO will quote the value and MySQL will
246 + // search the value as a string which prevents being able to do number-based operations
247 + // on the tag values. We ensure it has a numeric value and then cast it just to be sure.
248 + $tagValue = (float) trim($query->getConnection()->getPdo()->quote($tagValue), "'");
249 + $query->where('name', '=', $tagName)->whereRaw("value ${tagOperator} ${tagValue}");
250 + } else {
251 + $query->where('name', '=', $tagName)->where('value', $tagOperator, $tagValue);
252 + }
253 + } else {
254 + $query->where('name', '=', $tagName);
255 + }
256 + });
257 + }
258 + });
259 + return $query;
260 + }
261 +
262 +}
263 +
264 +
265 +
266 +
267 +
268 +
269 +
270 +
271 +
272 +
273 +
177 274
178 -}
...\ No newline at end of file ...\ No newline at end of file
......
...@@ -14,14 +14,17 @@ class PageRepo extends EntityRepo ...@@ -14,14 +14,17 @@ class PageRepo extends EntityRepo
14 { 14 {
15 15
16 protected $pageRevision; 16 protected $pageRevision;
17 + protected $tagRepo;
17 18
18 /** 19 /**
19 * PageRepo constructor. 20 * PageRepo constructor.
20 * @param PageRevision $pageRevision 21 * @param PageRevision $pageRevision
22 + * @param TagRepo $tagRepo
21 */ 23 */
22 - public function __construct(PageRevision $pageRevision) 24 + public function __construct(PageRevision $pageRevision, TagRepo $tagRepo)
23 { 25 {
24 $this->pageRevision = $pageRevision; 26 $this->pageRevision = $pageRevision;
27 + $this->tagRepo = $tagRepo;
25 parent::__construct(); 28 parent::__construct();
26 } 29 }
27 30
...@@ -142,6 +145,11 @@ class PageRepo extends EntityRepo ...@@ -142,6 +145,11 @@ class PageRepo extends EntityRepo
142 { 145 {
143 $draftPage->fill($input); 146 $draftPage->fill($input);
144 147
148 + // Save page tags if present
149 + if(isset($input['tags'])) {
150 + $this->tagRepo->saveTagsToEntity($draftPage, $input['tags']);
151 + }
152 +
145 $draftPage->slug = $this->findSuitableSlug($draftPage->name, $draftPage->book->id); 153 $draftPage->slug = $this->findSuitableSlug($draftPage->name, $draftPage->book->id);
146 $draftPage->html = $this->formatHtml($input['html']); 154 $draftPage->html = $this->formatHtml($input['html']);
147 $draftPage->text = strip_tags($draftPage->html); 155 $draftPage->text = strip_tags($draftPage->html);
...@@ -242,8 +250,9 @@ class PageRepo extends EntityRepo ...@@ -242,8 +250,9 @@ class PageRepo extends EntityRepo
242 public function getBySearch($term, $whereTerms = [], $count = 20, $paginationAppends = []) 250 public function getBySearch($term, $whereTerms = [], $count = 20, $paginationAppends = [])
243 { 251 {
244 $terms = $this->prepareSearchTerms($term); 252 $terms = $this->prepareSearchTerms($term);
245 - $pages = $this->permissionService->enforcePageRestrictions($this->page->fullTextSearchQuery(['name', 'text'], $terms, $whereTerms)) 253 + $pageQuery = $this->permissionService->enforcePageRestrictions($this->page->fullTextSearchQuery(['name', 'text'], $terms, $whereTerms));
246 - ->paginate($count)->appends($paginationAppends); 254 + $pageQuery = $this->addAdvancedSearchQueries($pageQuery, $term);
255 + $pages = $pageQuery->paginate($count)->appends($paginationAppends);
247 256
248 // Add highlights to page text. 257 // Add highlights to page text.
249 $words = join('|', explode(' ', preg_quote(trim($term), '/'))); 258 $words = join('|', explode(' ', preg_quote(trim($term), '/')));
...@@ -308,6 +317,11 @@ class PageRepo extends EntityRepo ...@@ -308,6 +317,11 @@ class PageRepo extends EntityRepo
308 $page->slug = $this->findSuitableSlug($input['name'], $book_id, $page->id); 317 $page->slug = $this->findSuitableSlug($input['name'], $book_id, $page->id);
309 } 318 }
310 319
320 + // Save page tags if present
321 + if(isset($input['tags'])) {
322 + $this->tagRepo->saveTagsToEntity($page, $input['tags']);
323 + }
324 +
311 // Update with new details 325 // Update with new details
312 $userId = auth()->user()->id; 326 $userId = auth()->user()->id;
313 $page->fill($input); 327 $page->fill($input);
...@@ -582,6 +596,7 @@ class PageRepo extends EntityRepo ...@@ -582,6 +596,7 @@ class PageRepo extends EntityRepo
582 { 596 {
583 Activity::removeEntity($page); 597 Activity::removeEntity($page);
584 $page->views()->delete(); 598 $page->views()->delete();
599 + $page->tags()->delete();
585 $page->revisions()->delete(); 600 $page->revisions()->delete();
586 $page->permissions()->delete(); 601 $page->permissions()->delete();
587 $this->permissionService->deleteJointPermissionsForEntity($page); 602 $this->permissionService->deleteJointPermissionsForEntity($page);
......
1 +<?php namespace BookStack\Repos;
2 +
3 +use BookStack\Tag;
4 +use BookStack\Entity;
5 +use BookStack\Services\PermissionService;
6 +
7 +/**
8 + * Class TagRepo
9 + * @package BookStack\Repos
10 + */
11 +class TagRepo
12 +{
13 +
14 + protected $tag;
15 + protected $entity;
16 + protected $permissionService;
17 +
18 + /**
19 + * TagRepo constructor.
20 + * @param Tag $attr
21 + * @param Entity $ent
22 + * @param PermissionService $ps
23 + */
24 + public function __construct(Tag $attr, Entity $ent, PermissionService $ps)
25 + {
26 + $this->tag = $attr;
27 + $this->entity = $ent;
28 + $this->permissionService = $ps;
29 + }
30 +
31 + /**
32 + * Get an entity instance of its particular type.
33 + * @param $entityType
34 + * @param $entityId
35 + * @param string $action
36 + */
37 + public function getEntity($entityType, $entityId, $action = 'view')
38 + {
39 + $entityInstance = $this->entity->getEntityInstance($entityType);
40 + $searchQuery = $entityInstance->where('id', '=', $entityId)->with('tags');
41 + $searchQuery = $this->permissionService->enforceEntityRestrictions($searchQuery, $action);
42 + return $searchQuery->first();
43 + }
44 +
45 + /**
46 + * Get all tags for a particular entity.
47 + * @param string $entityType
48 + * @param int $entityId
49 + * @return mixed
50 + */
51 + public function getForEntity($entityType, $entityId)
52 + {
53 + $entity = $this->getEntity($entityType, $entityId);
54 + if ($entity === null) return collect();
55 +
56 + return $entity->tags;
57 + }
58 +
59 + /**
60 + * Get tag name suggestions from scanning existing tag names.
61 + * @param $searchTerm
62 + * @return array
63 + */
64 + public function getNameSuggestions($searchTerm)
65 + {
66 + if ($searchTerm === '') return [];
67 + $query = $this->tag->where('name', 'LIKE', $searchTerm . '%')->groupBy('name')->orderBy('name', 'desc');
68 + $query = $this->permissionService->filterRestrictedEntityRelations($query, 'tags', 'entity_id', 'entity_type');
69 + return $query->get(['name'])->pluck('name');
70 + }
71 +
72 + /**
73 + * Get tag value suggestions from scanning existing tag values.
74 + * @param $searchTerm
75 + * @return array
76 + */
77 + public function getValueSuggestions($searchTerm)
78 + {
79 + if ($searchTerm === '') return [];
80 + $query = $this->tag->where('value', 'LIKE', $searchTerm . '%')->groupBy('value')->orderBy('value', 'desc');
81 + $query = $this->permissionService->filterRestrictedEntityRelations($query, 'tags', 'entity_id', 'entity_type');
82 + return $query->get(['value'])->pluck('value');
83 + }
84 + /**
85 + * Save an array of tags to an entity
86 + * @param Entity $entity
87 + * @param array $tags
88 + * @return array|\Illuminate\Database\Eloquent\Collection
89 + */
90 + public function saveTagsToEntity(Entity $entity, $tags = [])
91 + {
92 + $entity->tags()->delete();
93 + $newTags = [];
94 + foreach ($tags as $tag) {
95 + if (trim($tag['name']) === '') continue;
96 + $newTags[] = $this->newInstanceFromInput($tag);
97 + }
98 +
99 + return $entity->tags()->saveMany($newTags);
100 + }
101 +
102 + /**
103 + * Create a new Tag instance from user input.
104 + * @param $input
105 + * @return static
106 + */
107 + protected function newInstanceFromInput($input)
108 + {
109 + $name = trim($input['name']);
110 + $value = isset($input['value']) ? trim($input['value']) : '';
111 + // Any other modification or cleanup required can go here
112 + $values = ['name' => $name, 'value' => $value];
113 + return $this->tag->newInstance($values);
114 + }
115 +
116 +}
...\ No newline at end of file ...\ No newline at end of file
...@@ -400,9 +400,7 @@ class PermissionService ...@@ -400,9 +400,7 @@ class PermissionService
400 } 400 }
401 }); 401 });
402 402
403 - if ($this->isAdmin) return $query; 403 + return $this->enforceEntityRestrictions($query, $action);
404 - $this->currentAction = $action;
405 - return $this->entityRestrictionQuery($query);
406 } 404 }
407 405
408 /** 406 /**
...@@ -413,9 +411,7 @@ class PermissionService ...@@ -413,9 +411,7 @@ class PermissionService
413 */ 411 */
414 public function enforceChapterRestrictions($query, $action = 'view') 412 public function enforceChapterRestrictions($query, $action = 'view')
415 { 413 {
416 - if ($this->isAdmin) return $query; 414 + return $this->enforceEntityRestrictions($query, $action);
417 - $this->currentAction = $action;
418 - return $this->entityRestrictionQuery($query);
419 } 415 }
420 416
421 /** 417 /**
...@@ -426,6 +422,17 @@ class PermissionService ...@@ -426,6 +422,17 @@ class PermissionService
426 */ 422 */
427 public function enforceBookRestrictions($query, $action = 'view') 423 public function enforceBookRestrictions($query, $action = 'view')
428 { 424 {
425 + return $this->enforceEntityRestrictions($query, $action);
426 + }
427 +
428 + /**
429 + * Add restrictions for a generic entity
430 + * @param $query
431 + * @param string $action
432 + * @return mixed
433 + */
434 + public function enforceEntityRestrictions($query, $action = 'view')
435 + {
429 if ($this->isAdmin) return $query; 436 if ($this->isAdmin) return $query;
430 $this->currentAction = $action; 437 $this->currentAction = $action;
431 return $this->entityRestrictionQuery($query); 438 return $this->entityRestrictionQuery($query);
......
1 +<?php namespace BookStack;
2 +
3 +/**
4 + * Class Attribute
5 + * @package BookStack
6 + */
7 +class Tag extends Model
8 +{
9 + protected $fillable = ['name', 'value', 'order'];
10 +
11 + /**
12 + * Get the entity that this tag belongs to
13 + * @return \Illuminate\Database\Eloquent\Relations\MorphTo
14 + */
15 + public function entity()
16 + {
17 + return $this->morphTo('entity');
18 + }
19 +}
...\ No newline at end of file ...\ No newline at end of file
...@@ -52,4 +52,11 @@ $factory->define(BookStack\Role::class, function ($faker) { ...@@ -52,4 +52,11 @@ $factory->define(BookStack\Role::class, function ($faker) {
52 'display_name' => $faker->sentence(3), 52 'display_name' => $faker->sentence(3),
53 'description' => $faker->sentence(10) 53 'description' => $faker->sentence(10)
54 ]; 54 ];
55 +});
56 +
57 +$factory->define(BookStack\Tag::class, function ($faker) {
58 + return [
59 + 'name' => $faker->city,
60 + 'value' => $faker->sentence(3)
61 + ];
55 }); 62 });
...\ No newline at end of file ...\ No newline at end of file
......
1 +<?php
2 +
3 +use Illuminate\Database\Schema\Blueprint;
4 +use Illuminate\Database\Migrations\Migration;
5 +
6 +class CreateTagsTable extends Migration
7 +{
8 + /**
9 + * Run the migrations.
10 + *
11 + * @return void
12 + */
13 + public function up()
14 + {
15 + Schema::create('tags', function (Blueprint $table) {
16 + $table->increments('id');
17 + $table->integer('entity_id');
18 + $table->string('entity_type', 100);
19 + $table->string('name');
20 + $table->string('value');
21 + $table->integer('order');
22 + $table->timestamps();
23 +
24 + $table->index('name');
25 + $table->index('value');
26 + $table->index('order');
27 + $table->index(['entity_id', 'entity_type']);
28 + });
29 + }
30 +
31 + /**
32 + * Reverse the migrations.
33 + *
34 + * @return void
35 + */
36 + public function down()
37 + {
38 + Schema::drop('tags');
39 + }
40 +}
...@@ -4,10 +4,11 @@ ...@@ -4,10 +4,11 @@
4 "gulp": "^3.9.0" 4 "gulp": "^3.9.0"
5 }, 5 },
6 "dependencies": { 6 "dependencies": {
7 - "angular": "^1.5.0-rc.0", 7 + "angular": "^1.5.5",
8 - "angular-animate": "^1.5.0-rc.0", 8 + "angular-animate": "^1.5.5",
9 - "angular-resource": "^1.5.0-rc.0", 9 + "angular-resource": "^1.5.5",
10 - "angular-sanitize": "^1.5.0-rc.0", 10 + "angular-sanitize": "^1.5.5",
11 + "angular-ui-sortable": "^0.14.0",
11 "babel-runtime": "^5.8.29", 12 "babel-runtime": "^5.8.29",
12 "bootstrap-sass": "^3.0.0", 13 "bootstrap-sass": "^3.0.0",
13 "dropzone": "^4.0.1", 14 "dropzone": "^4.0.1",
......
...@@ -400,4 +400,116 @@ module.exports = function (ngApp, events) { ...@@ -400,4 +400,116 @@ module.exports = function (ngApp, events) {
400 400
401 }]); 401 }]);
402 402
403 -};
...\ No newline at end of file ...\ No newline at end of file
403 + ngApp.controller('PageTagController', ['$scope', '$http', '$attrs',
404 + function ($scope, $http, $attrs) {
405 +
406 + const pageId = Number($attrs.pageId);
407 + $scope.tags = [];
408 +
409 + $scope.sortOptions = {
410 + handle: '.handle',
411 + items: '> tr',
412 + containment: "parent",
413 + axis: "y"
414 + };
415 +
416 + /**
417 + * Push an empty tag to the end of the scope tags.
418 + */
419 + function addEmptyTag() {
420 + $scope.tags.push({
421 + name: '',
422 + value: ''
423 + });
424 + }
425 + $scope.addEmptyTag = addEmptyTag;
426 +
427 + /**
428 + * Get all tags for the current book and add into scope.
429 + */
430 + function getTags() {
431 + $http.get('/ajax/tags/get/page/' + pageId).then((responseData) => {
432 + $scope.tags = responseData.data;
433 + addEmptyTag();
434 + });
435 + }
436 + getTags();
437 +
438 + /**
439 + * Set the order property on all tags.
440 + */
441 + function setTagOrder() {
442 + for (let i = 0; i < $scope.tags.length; i++) {
443 + $scope.tags[i].order = i;
444 + }
445 + }
446 +
447 + /**
448 + * When an tag changes check if another empty editable
449 + * field needs to be added onto the end.
450 + * @param tag
451 + */
452 + $scope.tagChange = function(tag) {
453 + let cPos = $scope.tags.indexOf(tag);
454 + if (cPos !== $scope.tags.length-1) return;
455 +
456 + if (tag.name !== '' || tag.value !== '') {
457 + addEmptyTag();
458 + }
459 + };
460 +
461 + /**
462 + * When an tag field loses focus check the tag to see if its
463 + * empty and therefore could be removed from the list.
464 + * @param tag
465 + */
466 + $scope.tagBlur = function(tag) {
467 + let isLast = $scope.tags.length - 1 === $scope.tags.indexOf(tag);
468 + if (tag.name === '' && tag.value === '' && !isLast) {
469 + let cPos = $scope.tags.indexOf(tag);
470 + $scope.tags.splice(cPos, 1);
471 + }
472 + };
473 +
474 + /**
475 + * Save the tags to the current page.
476 + */
477 + $scope.saveTags = function() {
478 + setTagOrder();
479 + let postData = {tags: $scope.tags};
480 + $http.post('/ajax/tags/update/page/' + pageId, postData).then((responseData) => {
481 + $scope.tags = responseData.data.tags;
482 + addEmptyTag();
483 + events.emit('success', responseData.data.message);
484 + })
485 + };
486 +
487 + /**
488 + * Remove a tag from the current list.
489 + * @param tag
490 + */
491 + $scope.removeTag = function(tag) {
492 + let cIndex = $scope.tags.indexOf(tag);
493 + $scope.tags.splice(cIndex, 1);
494 + };
495 +
496 + }]);
497 +
498 +};
499 +
500 +
501 +
502 +
503 +
504 +
505 +
506 +
507 +
508 +
509 +
510 +
511 +
512 +
513 +
514 +
515 +
......
...@@ -301,6 +301,219 @@ module.exports = function (ngApp, events) { ...@@ -301,6 +301,219 @@ module.exports = function (ngApp, events) {
301 301
302 } 302 }
303 } 303 }
304 - }]) 304 + }]);
305 +
306 + ngApp.directive('toolbox', [function() {
307 + return {
308 + restrict: 'A',
309 + link: function(scope, elem, attrs) {
310 +
311 + // Get common elements
312 + const $buttons = elem.find('[tab-button]');
313 + const $content = elem.find('[tab-content]');
314 + const $toggle = elem.find('[toolbox-toggle]');
315 +
316 + // Handle toolbox toggle click
317 + $toggle.click((e) => {
318 + elem.toggleClass('open');
319 + });
320 +
321 + // Set an active tab/content by name
322 + function setActive(tabName, openToolbox) {
323 + $buttons.removeClass('active');
324 + $content.hide();
325 + $buttons.filter(`[tab-button="${tabName}"]`).addClass('active');
326 + $content.filter(`[tab-content="${tabName}"]`).show();
327 + if (openToolbox) elem.addClass('open');
328 + }
329 +
330 + // Set the first tab content active on load
331 + setActive($content.first().attr('tab-content'), false);
332 +
333 + // Handle tab button click
334 + $buttons.click(function(e) {
335 + let name = $(this).attr('tab-button');
336 + setActive(name, true);
337 + });
338 + }
339 + }
340 + }]);
341 +
342 + ngApp.directive('autosuggestions', ['$http', function($http) {
343 + return {
344 + restrict: 'A',
345 + link: function(scope, elem, attrs) {
346 +
347 + // Local storage for quick caching.
348 + const localCache = {};
349 +
350 + // Create suggestion element
351 + const suggestionBox = document.createElement('ul');
352 + suggestionBox.className = 'suggestion-box';
353 + suggestionBox.style.position = 'absolute';
354 + suggestionBox.style.display = 'none';
355 + const $suggestionBox = $(suggestionBox);
356 +
357 + // General state tracking
358 + let isShowing = false;
359 + let currentInput = false;
360 + let active = 0;
361 +
362 + // Listen to input events on autosuggest fields
363 + elem.on('input', '[autosuggest]', function(event) {
364 + let $input = $(this);
365 + let val = $input.val();
366 + let url = $input.attr('autosuggest');
367 + // No suggestions until at least 3 chars
368 + if (val.length < 3) {
369 + if (isShowing) {
370 + $suggestionBox.hide();
371 + isShowing = false;
372 + }
373 + return;
374 + };
375 +
376 + let suggestionPromise = getSuggestions(val.slice(0, 3), url);
377 + suggestionPromise.then((suggestions) => {
378 + if (val.length > 2) {
379 + suggestions = suggestions.filter((item) => {
380 + return item.toLowerCase().indexOf(val.toLowerCase()) !== -1;
381 + }).slice(0, 4);
382 + displaySuggestions($input, suggestions);
383 + }
384 + });
385 + });
386 +
387 + // Hide autosuggestions when input loses focus.
388 + // Slight delay to allow clicks.
389 + elem.on('blur', '[autosuggest]', function(event) {
390 + setTimeout(() => {
391 + $suggestionBox.hide();
392 + isShowing = false;
393 + }, 200)
394 + });
395 +
396 + elem.on('keydown', '[autosuggest]', function (event) {
397 + if (!isShowing) return;
398 +
399 + let suggestionElems = suggestionBox.childNodes;
400 + let suggestCount = suggestionElems.length;
401 +
402 + // Down arrow
403 + if (event.keyCode === 40) {
404 + let newActive = (active === suggestCount-1) ? 0 : active + 1;
405 + changeActiveTo(newActive, suggestionElems);
406 + }
407 + // Up arrow
408 + else if (event.keyCode === 38) {
409 + let newActive = (active === 0) ? suggestCount-1 : active - 1;
410 + changeActiveTo(newActive, suggestionElems);
411 + }
412 + // Enter key
413 + else if (event.keyCode === 13) {
414 + let text = suggestionElems[active].textContent;
415 + currentInput[0].value = text;
416 + currentInput.focus();
417 + $suggestionBox.hide();
418 + isShowing = false;
419 + event.preventDefault();
420 + return false;
421 + }
422 + });
423 +
424 + // Change the active suggestion to the given index
425 + function changeActiveTo(index, suggestionElems) {
426 + suggestionElems[active].className = '';
427 + active = index;
428 + suggestionElems[active].className = 'active';
429 + }
430 +
431 + // Display suggestions on a field
432 + let prevSuggestions = [];
433 + function displaySuggestions($input, suggestions) {
434 +
435 + // Hide if no suggestions
436 + if (suggestions.length === 0) {
437 + $suggestionBox.hide();
438 + isShowing = false;
439 + prevSuggestions = suggestions;
440 + return;
441 + }
442 +
443 + // Otherwise show and attach to input
444 + if (!isShowing) {
445 + $suggestionBox.show();
446 + isShowing = true;
447 + }
448 + if ($input !== currentInput) {
449 + $suggestionBox.detach();
450 + $input.after($suggestionBox);
451 + currentInput = $input;
452 + }
453 +
454 + // Return if no change
455 + if (prevSuggestions.join() === suggestions.join()) {
456 + prevSuggestions = suggestions;
457 + return;
458 + }
459 +
460 + // Build suggestions
461 + $suggestionBox[0].innerHTML = '';
462 + for (let i = 0; i < suggestions.length; i++) {
463 + var suggestion = document.createElement('li');
464 + suggestion.textContent = suggestions[i];
465 + suggestion.onclick = suggestionClick;
466 + if (i === 0) {
467 + suggestion.className = 'active'
468 + active = 0;
469 + };
470 + $suggestionBox[0].appendChild(suggestion);
471 + }
472 +
473 + prevSuggestions = suggestions;
474 + }
475 +
476 + // Suggestion click event
477 + function suggestionClick(event) {
478 + let text = this.textContent;
479 + currentInput[0].value = text;
480 + currentInput.focus();
481 + $suggestionBox.hide();
482 + isShowing = false;
483 + };
484 +
485 + // Get suggestions & cache
486 + function getSuggestions(input, url) {
487 + let searchUrl = url + '?search=' + encodeURIComponent(input);
488 +
489 + // Get from local cache if exists
490 + if (localCache[searchUrl]) {
491 + return new Promise((resolve, reject) => {
492 + resolve(localCache[input]);
493 + });
494 + }
495 +
496 + return $http.get(searchUrl).then((response) => {
497 + localCache[input] = response.data;
498 + return response.data;
499 + });
500 + }
501 +
502 + }
503 + }
504 + }]);
505 +};
506 +
507 +
508 +
509 +
510 +
511 +
512 +
513 +
514 +
515 +
516 +
517 +
518 +
305 519
306 -};
...\ No newline at end of file ...\ No newline at end of file
......
...@@ -5,9 +5,9 @@ var angular = require('angular'); ...@@ -5,9 +5,9 @@ var angular = require('angular');
5 var ngResource = require('angular-resource'); 5 var ngResource = require('angular-resource');
6 var ngAnimate = require('angular-animate'); 6 var ngAnimate = require('angular-animate');
7 var ngSanitize = require('angular-sanitize'); 7 var ngSanitize = require('angular-sanitize');
8 +require('angular-ui-sortable');
8 9
9 -var ngApp = angular.module('bookStack', ['ngResource', 'ngAnimate', 'ngSanitize']); 10 +var ngApp = angular.module('bookStack', ['ngResource', 'ngAnimate', 'ngSanitize', 'ui.sortable']);
10 -
11 11
12 // Global Event System 12 // Global Event System
13 var Events = { 13 var Events = {
......
...@@ -65,6 +65,9 @@ $button-border-radius: 2px; ...@@ -65,6 +65,9 @@ $button-border-radius: 2px;
65 &:focus, &:active { 65 &:focus, &:active {
66 outline: 0; 66 outline: 0;
67 } 67 }
68 + &:hover {
69 + text-decoration: none;
70 + }
68 &.neg { 71 &.neg {
69 color: $negative; 72 color: $negative;
70 } 73 }
......
...@@ -239,6 +239,17 @@ div[editor-type="markdown"] .title-input.page-title input[type="text"] { ...@@ -239,6 +239,17 @@ div[editor-type="markdown"] .title-input.page-title input[type="text"] {
239 } 239 }
240 } 240 }
241 241
242 +input.outline {
243 + border: 0;
244 + border-bottom: 2px solid #DDD;
245 + border-radius: 0;
246 + &:focus, &:active {
247 + border: 0;
248 + border-bottom: 2px solid #AAA;
249 + outline: 0;
250 + }
251 +}
252 +
242 #login-form label[for="remember"] { 253 #login-form label[for="remember"] {
243 margin: 0; 254 margin: 0;
244 } 255 }
......
...@@ -122,9 +122,176 @@ ...@@ -122,9 +122,176 @@
122 } 122 }
123 } 123 }
124 124
125 -h1, h2, h3, h4, h5, h6 { 125 +// Attribute form
126 - &:hover a.link-hook { 126 +.floating-toolbox {
127 - opacity: 1; 127 + background-color: #FFF;
128 - transform: translate3d(0, 0, 0); 128 + border: 1px solid #DDD;
129 + right: $-xl*2;
130 + z-index: 99;
131 + width: 48px;
132 + overflow: hidden;
133 + align-items: stretch;
134 + flex-direction: row;
135 + display: flex;
136 + transition: width ease-in-out 180ms;
137 + margin-top: -1px;
138 + &.open {
139 + width: 480px;
140 + }
141 + [toolbox-toggle] i {
142 + transition: transform ease-in-out 180ms;
143 + }
144 + [toolbox-toggle] {
145 + transition: background-color ease-in-out 180ms;
146 + }
147 + &.open [toolbox-toggle] {
148 + background-color: rgba(255, 0, 0, 0.29);
149 + }
150 + &.open [toolbox-toggle] i {
151 + transform: rotate(180deg);
152 + }
153 + > div {
154 + flex: 1;
155 + position: relative;
156 + }
157 + .tabs {
158 + display: block;
159 + border-right: 1px solid #DDD;
160 + width: 54px;
161 + flex: 0;
162 + }
163 + .tabs i {
164 + color: rgba(0, 0, 0, 0.5);
165 + padding: 0;
166 + margin: 0;
167 + }
168 + .tabs > span {
169 + display: block;
170 + cursor: pointer;
171 + padding: $-s $-m;
172 + font-size: 13.5px;
173 + line-height: 1.6;
174 + border-bottom: 1px solid rgba(255, 255, 255, 0.3);
129 } 175 }
176 + &.open .tabs > span.active {
177 + color: #444;
178 + background-color: rgba(0, 0, 0, 0.1);
179 + }
180 + div[tab-content] {
181 + padding-bottom: 45px;
182 + display: flex;
183 + flex: 1;
184 + flex-direction: column;
185 + }
186 + div[tab-content] .padded {
187 + flex: 1;
188 + padding-top: 0;
189 + }
190 + h4 {
191 + font-size: 24px;
192 + margin: $-m 0 0 0;
193 + padding: 0 $-l $-s $-l;
194 + }
195 + .tags input {
196 + max-width: 100%;
197 + width: 100%;
198 + min-width: 50px;
199 + }
200 + .tags td {
201 + padding-right: $-s;
202 + padding-top: $-s;
203 + position: relative;
204 + }
205 + button.pos {
206 + position: absolute;
207 + bottom: 0;
208 + display: block;
209 + width: 100%;
210 + padding: $-s;
211 + height: 45px;
212 + border: 0;
213 + margin: 0;
214 + box-shadow: none;
215 + border-radius: 0;
216 + &:hover{
217 + box-shadow: none;
218 + }
219 + }
220 + .handle {
221 + user-select: none;
222 + cursor: move;
223 + color: #999;
224 + }
225 + form {
226 + display: flex;
227 + flex: 1;
228 + flex-direction: column;
229 + overflow-y: scroll;
230 + }
231 +}
232 +
233 +[tab-content] {
234 + display: none;
130 } 235 }
236 +
237 +.tag-display {
238 + margin: $-xl $-xs;
239 + border: 1px solid #DDD;
240 + min-width: 180px;
241 + max-width: 320px;
242 + opacity: 0.7;
243 + table {
244 + width: 100%;
245 + margin: 0;
246 + padding: 0;
247 + }
248 + span {
249 + color: #666;
250 + margin-left: $-s;
251 + }
252 + .heading {
253 + padding: $-xs $-s;
254 + color: #444;
255 + }
256 + td {
257 + border: 0;
258 + border-bottom: 1px solid #DDD;
259 + padding: $-xs $-s;
260 + color: #444;
261 + }
262 + .tag-value {
263 + color: #888;
264 + }
265 + td i {
266 + color: #888;
267 + }
268 + tr:last-child td {
269 + border-bottom: none;
270 + }
271 + .tag {
272 + padding: $-s;
273 + }
274 +}
275 +
276 +.suggestion-box {
277 + position: absolute;
278 + background-color: #FFF;
279 + border: 1px solid #BBB;
280 + box-shadow: $bs-light;
281 + list-style: none;
282 + z-index: 100;
283 + padding: 0;
284 + margin: 0;
285 + border-radius: 3px;
286 + li {
287 + display: block;
288 + padding: $-xs $-s;
289 + border-bottom: 1px solid #DDD;
290 + &:last-child {
291 + border-bottom: 0;
292 + }
293 + &.active {
294 + background-color: #EEE;
295 + }
296 + }
297 +}
...\ No newline at end of file ...\ No newline at end of file
......
...@@ -26,6 +26,13 @@ table { ...@@ -26,6 +26,13 @@ table {
26 } 26 }
27 } 27 }
28 28
29 +table.no-style {
30 + td {
31 + border: 0;
32 + padding: 0;
33 + }
34 +}
35 +
29 table.list-table { 36 table.list-table {
30 margin: 0 -$-xs; 37 margin: 0 -$-xs;
31 td { 38 td {
......
...@@ -21,6 +21,11 @@ ...@@ -21,6 +21,11 @@
21 21
22 [ng\:cloak], [ng-cloak], .ng-cloak { 22 [ng\:cloak], [ng-cloak], .ng-cloak {
23 display: none !important; 23 display: none !important;
24 + user-select: none;
25 +}
26 +
27 +[ng-click] {
28 + cursor: pointer;
24 } 29 }
25 30
26 // Jquery Sortable Styles 31 // Jquery Sortable Styles
...@@ -201,4 +206,4 @@ $btt-size: 40px; ...@@ -201,4 +206,4 @@ $btt-size: 40px;
201 background-color: $negative; 206 background-color: $negative;
202 color: #EEE; 207 color: #EEE;
203 } 208 }
204 -}
...\ No newline at end of file ...\ No newline at end of file
209 +}
......
...@@ -15,6 +15,7 @@ ...@@ -15,6 +15,7 @@
15 15
16 <!-- Scripts --> 16 <!-- Scripts -->
17 <script src="/libs/jquery/jquery.min.js?version=2.1.4"></script> 17 <script src="/libs/jquery/jquery.min.js?version=2.1.4"></script>
18 + <script src="/libs/jquery/jquery-ui.min.js?version=1.11.4"></script>
18 19
19 @yield('head') 20 @yield('head')
20 21
......
1 -@extends('base')
2 -
3 -@section('head')
4 - <script src="/libs/tinymce/tinymce.min.js?ver=4.3.7"></script>
5 -@stop
6 -
7 -@section('body-class', 'flexbox')
8 -
9 -@section('content')
10 -
11 - <div class="flex-fill flex">
12 - <form action="{{$book->getUrl() . '/page/' . $draft->id}}" method="POST" class="flex flex-fill">
13 - @include('pages/form', ['model' => $draft])
14 - </form>
15 - </div>
16 - @include('partials/image-manager', ['imageType' => 'gallery', 'uploaded_to' => $draft->id])
17 -@stop
...\ No newline at end of file ...\ No newline at end of file
...@@ -9,10 +9,15 @@ ...@@ -9,10 +9,15 @@
9 @section('content') 9 @section('content')
10 10
11 <div class="flex-fill flex"> 11 <div class="flex-fill flex">
12 - <form action="{{$page->getUrl()}}" data-page-id="{{ $page->id }}" method="POST" class="flex flex-fill"> 12 + <form action="{{$page->getUrl()}}" autocomplete="off" data-page-id="{{ $page->id }}" method="POST" class="flex flex-fill">
13 - <input type="hidden" name="_method" value="PUT"> 13 + @if(!isset($isDraft))
14 + <input type="hidden" name="_method" value="PUT">
15 + @endif
14 @include('pages/form', ['model' => $page]) 16 @include('pages/form', ['model' => $page])
17 + @include('pages/form-toolbox')
15 </form> 18 </form>
19 +
20 +
16 </div> 21 </div>
17 @include('partials/image-manager', ['imageType' => 'gallery', 'uploaded_to' => $page->id]) 22 @include('partials/image-manager', ['imageType' => 'gallery', 'uploaded_to' => $page->id])
18 23
......
1 +
2 +<div toolbox class="floating-toolbox">
3 +
4 + <div class="tabs primary-background-light">
5 + <span toolbox-toggle><i class="zmdi zmdi-caret-left-circle"></i></span>
6 + <span tab-button="tags" title="Page Tags" class="active"><i class="zmdi zmdi-tag"></i></span>
7 + </div>
8 +
9 + <div tab-content="tags" ng-controller="PageTagController" page-id="{{ $page->id or 0 }}">
10 + <h4>Page Tags</h4>
11 + <div class="padded tags">
12 + <p class="muted small">Add some tags to better categorise your content. <br> You can assign a value to a tag for more in-depth organisation.</p>
13 + <table class="no-style" autosuggestions style="width: 100%;">
14 + <tbody ui-sortable="sortOptions" ng-model="tags" >
15 + <tr ng-repeat="tag in tags track by $index">
16 + <td width="20" ><i class="handle zmdi zmdi-menu"></i></td>
17 + <td><input autosuggest="/ajax/tags/suggest/names" class="outline" ng-attr-name="tags[@{{$index}}][name]" type="text" ng-model="tag.name" ng-change="tagChange(tag)" ng-blur="tagBlur(tag)" placeholder="Tag"></td>
18 + <td><input autosuggest="/ajax/tags/suggest/values" class="outline" ng-attr-name="tags[@{{$index}}][value]" type="text" ng-model="tag.value" ng-change="tagChange(tag)" ng-blur="tagBlur(tag)" placeholder="Tag Value (Optional)"></td>
19 + <td width="10" ng-show="tags.length != 1" class="text-center text-neg" style="padding: 0;" ng-click="removeTag(tag)"><i class="zmdi zmdi-close"></i></td>
20 + </tr>
21 + </tbody>
22 + </table>
23 + <table class="no-style" style="width: 100%;">
24 + <tbody>
25 + <tr class="unsortable">
26 + <td width="34"></td>
27 + <td ng-click="addEmptyTag()">
28 + <button type="button" class="text-button">Add another tag</button>
29 + </td>
30 + <td></td>
31 + </tr>
32 + </tbody>
33 + </table>
34 + </div>
35 + </div>
36 +
37 +</div>
...\ No newline at end of file ...\ No newline at end of file
...@@ -41,6 +41,7 @@ ...@@ -41,6 +41,7 @@
41 @include('form/text', ['name' => 'name', 'placeholder' => 'Page Title']) 41 @include('form/text', ['name' => 'name', 'placeholder' => 'Page Title'])
42 </div> 42 </div>
43 </div> 43 </div>
44 +
44 <div class="edit-area flex-fill flex"> 45 <div class="edit-area flex-fill flex">
45 @if(setting('app-editor') === 'wysiwyg') 46 @if(setting('app-editor') === 'wysiwyg')
46 <textarea id="html-editor" tinymce="editorOptions" mce-change="editorChange" mce-model="editContent" name="html" rows="5" 47 <textarea id="html-editor" tinymce="editorOptions" mce-change="editorChange" mce-model="editContent" name="html" rows="5"
......
1 <div ng-non-bindable> 1 <div ng-non-bindable>
2 - <h1 id="bkmrk-page-title">{{$page->name}}</h1> 2 +
3 + <h1 id="bkmrk-page-title" class="float left">{{$page->name}}</h1>
4 +
5 + @if(count($page->tags) > 0)
6 + <div class="tag-display float right">
7 + <div class="heading primary-background-light">Page Tags</div>
8 + <table>
9 + @foreach($page->tags as $tag)
10 + <tr class="tag">
11 + <td @if(!$tag->value) colspan="2" @endif><a href="/search/all?term=%5B{{ urlencode($tag->name) }}%5D">{{ $tag->name }}</a></td>
12 + @if($tag->value) <td class="tag-value"><a href="/search/all?term=%5B{{ urlencode($tag->name) }}%3D{{ urlencode($tag->value) }}%5D">{{$tag->value}}</a></td> @endif
13 + </tr>
14 + @endforeach
15 + </table>
16 + </div>
17 + @endif
18 +
19 + <div style="clear:left;"></div>
3 20
4 {!! $page->html !!} 21 {!! $page->html !!}
5 </div> 22 </div>
...\ No newline at end of file ...\ No newline at end of file
......
1 @if(Setting::get('app-color')) 1 @if(Setting::get('app-color'))
2 <style> 2 <style>
3 - header, #back-to-top { 3 + header, #back-to-top, .primary-background {
4 background-color: {{ Setting::get('app-color') }}; 4 background-color: {{ Setting::get('app-color') }};
5 } 5 }
6 - .faded-small { 6 + .faded-small, .primary-background-light {
7 background-color: {{ Setting::get('app-color-light') }}; 7 background-color: {{ Setting::get('app-color-light') }};
8 } 8 }
9 .button-base, .button, input[type="button"], input[type="submit"] { 9 .button-base, .button, input[type="button"], input[type="submit"] {
...@@ -15,7 +15,7 @@ ...@@ -15,7 +15,7 @@
15 .nav-tabs a.selected, .nav-tabs .tab-item.selected { 15 .nav-tabs a.selected, .nav-tabs .tab-item.selected {
16 border-bottom-color: {{ Setting::get('app-color') }}; 16 border-bottom-color: {{ Setting::get('app-color') }};
17 } 17 }
18 - p.primary:hover, p .primary:hover, span.primary:hover, .text-primary:hover, a, a:hover, a:focus { 18 + p.primary:hover, p .primary:hover, span.primary:hover, .text-primary:hover, a, a:hover, a:focus, .text-button, .text-button:hover, .text-button:focus {
19 color: {{ Setting::get('app-color') }}; 19 color: {{ Setting::get('app-color') }};
20 } 20 }
21 </style> 21 </style>
......
...@@ -181,7 +181,7 @@ class AuthTest extends TestCase ...@@ -181,7 +181,7 @@ class AuthTest extends TestCase
181 public function test_user_deletion() 181 public function test_user_deletion()
182 { 182 {
183 $userDetails = factory(\BookStack\User::class)->make(); 183 $userDetails = factory(\BookStack\User::class)->make();
184 - $user = $this->getNewUser($userDetails->toArray()); 184 + $user = $this->getEditor($userDetails->toArray());
185 185
186 $this->asAdmin() 186 $this->asAdmin()
187 ->visit('/settings/users/' . $user->id) 187 ->visit('/settings/users/' . $user->id)
......
...@@ -161,8 +161,8 @@ class EntityTest extends TestCase ...@@ -161,8 +161,8 @@ class EntityTest extends TestCase
161 public function test_entities_viewable_after_creator_deletion() 161 public function test_entities_viewable_after_creator_deletion()
162 { 162 {
163 // Create required assets and revisions 163 // Create required assets and revisions
164 - $creator = $this->getNewUser(); 164 + $creator = $this->getEditor();
165 - $updater = $this->getNewUser(); 165 + $updater = $this->getEditor();
166 $entities = $this->createEntityChainBelongingToUser($creator, $updater); 166 $entities = $this->createEntityChainBelongingToUser($creator, $updater);
167 $this->actingAs($creator); 167 $this->actingAs($creator);
168 app('BookStack\Repos\UserRepo')->destroy($creator); 168 app('BookStack\Repos\UserRepo')->destroy($creator);
...@@ -174,8 +174,8 @@ class EntityTest extends TestCase ...@@ -174,8 +174,8 @@ class EntityTest extends TestCase
174 public function test_entities_viewable_after_updater_deletion() 174 public function test_entities_viewable_after_updater_deletion()
175 { 175 {
176 // Create required assets and revisions 176 // Create required assets and revisions
177 - $creator = $this->getNewUser(); 177 + $creator = $this->getEditor();
178 - $updater = $this->getNewUser(); 178 + $updater = $this->getEditor();
179 $entities = $this->createEntityChainBelongingToUser($creator, $updater); 179 $entities = $this->createEntityChainBelongingToUser($creator, $updater);
180 $this->actingAs($updater); 180 $this->actingAs($updater);
181 app('BookStack\Repos\UserRepo')->destroy($updater); 181 app('BookStack\Repos\UserRepo')->destroy($updater);
...@@ -198,7 +198,7 @@ class EntityTest extends TestCase ...@@ -198,7 +198,7 @@ class EntityTest extends TestCase
198 198
199 public function test_recently_created_pages_view() 199 public function test_recently_created_pages_view()
200 { 200 {
201 - $user = $this->getNewUser(); 201 + $user = $this->getEditor();
202 $content = $this->createEntityChainBelongingToUser($user); 202 $content = $this->createEntityChainBelongingToUser($user);
203 203
204 $this->asAdmin()->visit('/pages/recently-created') 204 $this->asAdmin()->visit('/pages/recently-created')
...@@ -207,7 +207,7 @@ class EntityTest extends TestCase ...@@ -207,7 +207,7 @@ class EntityTest extends TestCase
207 207
208 public function test_recently_updated_pages_view() 208 public function test_recently_updated_pages_view()
209 { 209 {
210 - $user = $this->getNewUser(); 210 + $user = $this->getEditor();
211 $content = $this->createEntityChainBelongingToUser($user); 211 $content = $this->createEntityChainBelongingToUser($user);
212 212
213 $this->asAdmin()->visit('/pages/recently-updated') 213 $this->asAdmin()->visit('/pages/recently-updated')
...@@ -241,7 +241,7 @@ class EntityTest extends TestCase ...@@ -241,7 +241,7 @@ class EntityTest extends TestCase
241 241
242 public function test_recently_created_pages_on_home() 242 public function test_recently_created_pages_on_home()
243 { 243 {
244 - $entityChain = $this->createEntityChainBelongingToUser($this->getNewUser()); 244 + $entityChain = $this->createEntityChainBelongingToUser($this->getEditor());
245 $this->asAdmin()->visit('/') 245 $this->asAdmin()->visit('/')
246 ->seeInElement('#recently-created-pages', $entityChain['page']->name); 246 ->seeInElement('#recently-created-pages', $entityChain['page']->name);
247 } 247 }
......
...@@ -32,7 +32,7 @@ class PageDraftTest extends TestCase ...@@ -32,7 +32,7 @@ class PageDraftTest extends TestCase
32 ->dontSeeInField('html', $addedContent); 32 ->dontSeeInField('html', $addedContent);
33 33
34 $newContent = $this->page->html . $addedContent; 34 $newContent = $this->page->html . $addedContent;
35 - $newUser = $this->getNewUser(); 35 + $newUser = $this->getEditor();
36 $this->pageRepo->saveUpdateDraft($this->page, ['html' => $newContent]); 36 $this->pageRepo->saveUpdateDraft($this->page, ['html' => $newContent]);
37 $this->actingAs($newUser)->visit($this->page->getUrl() . '/edit') 37 $this->actingAs($newUser)->visit($this->page->getUrl() . '/edit')
38 ->dontSeeInField('html', $newContent); 38 ->dontSeeInField('html', $newContent);
...@@ -54,7 +54,7 @@ class PageDraftTest extends TestCase ...@@ -54,7 +54,7 @@ class PageDraftTest extends TestCase
54 ->dontSeeInField('html', $addedContent); 54 ->dontSeeInField('html', $addedContent);
55 55
56 $newContent = $this->page->html . $addedContent; 56 $newContent = $this->page->html . $addedContent;
57 - $newUser = $this->getNewUser(); 57 + $newUser = $this->getEditor();
58 $this->pageRepo->saveUpdateDraft($this->page, ['html' => $newContent]); 58 $this->pageRepo->saveUpdateDraft($this->page, ['html' => $newContent]);
59 59
60 $this->actingAs($newUser) 60 $this->actingAs($newUser)
...@@ -79,7 +79,7 @@ class PageDraftTest extends TestCase ...@@ -79,7 +79,7 @@ class PageDraftTest extends TestCase
79 { 79 {
80 $book = \BookStack\Book::first(); 80 $book = \BookStack\Book::first();
81 $chapter = $book->chapters->first(); 81 $chapter = $book->chapters->first();
82 - $newUser = $this->getNewUser(); 82 + $newUser = $this->getEditor();
83 83
84 $this->actingAs($newUser)->visit('/') 84 $this->actingAs($newUser)->visit('/')
85 ->visit($book->getUrl() . '/page/create') 85 ->visit($book->getUrl() . '/page/create')
......
1 +<?php namespace Entity;
2 +
3 +use BookStack\Tag;
4 +use BookStack\Page;
5 +use BookStack\Services\PermissionService;
6 +
7 +class TagTests extends \TestCase
8 +{
9 +
10 + protected $defaultTagCount = 20;
11 +
12 + /**
13 + * Get an instance of a page that has many tags.
14 + * @param Tag[]|bool $tags
15 + * @return mixed
16 + */
17 + protected function getPageWithTags($tags = false)
18 + {
19 + $page = Page::first();
20 +
21 + if (!$tags) {
22 + $tags = factory(Tag::class, $this->defaultTagCount)->make();
23 + }
24 +
25 + $page->tags()->saveMany($tags);
26 + return $page;
27 + }
28 +
29 + public function test_get_page_tags()
30 + {
31 + $page = $this->getPageWithTags();
32 +
33 + // Add some other tags to check they don't interfere
34 + factory(Tag::class, $this->defaultTagCount)->create();
35 +
36 + $this->asAdmin()->get("/ajax/tags/get/page/" . $page->id)
37 + ->shouldReturnJson();
38 +
39 + $json = json_decode($this->response->getContent());
40 + $this->assertTrue(count($json) === $this->defaultTagCount, "Returned JSON item count is not as expected");
41 + }
42 +
43 + public function test_tag_name_suggestions()
44 + {
45 + // Create some tags with similar names to test with
46 + $attrs = collect();
47 + $attrs = $attrs->merge(factory(Tag::class, 5)->make(['name' => 'country']));
48 + $attrs = $attrs->merge(factory(Tag::class, 5)->make(['name' => 'color']));
49 + $attrs = $attrs->merge(factory(Tag::class, 5)->make(['name' => 'city']));
50 + $attrs = $attrs->merge(factory(Tag::class, 5)->make(['name' => 'county']));
51 + $attrs = $attrs->merge(factory(Tag::class, 5)->make(['name' => 'planet']));
52 + $attrs = $attrs->merge(factory(Tag::class, 5)->make(['name' => 'plans']));
53 + $page = $this->getPageWithTags($attrs);
54 +
55 + $this->asAdmin()->get('/ajax/tags/suggest/names?search=dog')->seeJsonEquals([]);
56 + $this->get('/ajax/tags/suggest/names?search=co')->seeJsonEquals(['color', 'country', 'county']);
57 + $this->get('/ajax/tags/suggest/names?search=cou')->seeJsonEquals(['country', 'county']);
58 + $this->get('/ajax/tags/suggest/names?search=pla')->seeJsonEquals(['planet', 'plans']);
59 + }
60 +
61 + public function test_tag_value_suggestions()
62 + {
63 + // Create some tags with similar values to test with
64 + $attrs = collect();
65 + $attrs = $attrs->merge(factory(Tag::class, 5)->make(['name' => 'country', 'value' => 'cats']));
66 + $attrs = $attrs->merge(factory(Tag::class, 5)->make(['name' => 'color', 'value' => 'cattery']));
67 + $attrs = $attrs->merge(factory(Tag::class, 5)->make(['name' => 'city', 'value' => 'castle']));
68 + $attrs = $attrs->merge(factory(Tag::class, 5)->make(['name' => 'county', 'value' => 'dog']));
69 + $attrs = $attrs->merge(factory(Tag::class, 5)->make(['name' => 'planet', 'value' => 'catapult']));
70 + $attrs = $attrs->merge(factory(Tag::class, 5)->make(['name' => 'plans', 'value' => 'dodgy']));
71 + $page = $this->getPageWithTags($attrs);
72 +
73 + $this->asAdmin()->get('/ajax/tags/suggest/values?search=ora')->seeJsonEquals([]);
74 + $this->get('/ajax/tags/suggest/values?search=cat')->seeJsonEquals(['cats', 'cattery', 'catapult']);
75 + $this->get('/ajax/tags/suggest/values?search=do')->seeJsonEquals(['dog', 'dodgy']);
76 + $this->get('/ajax/tags/suggest/values?search=cas')->seeJsonEquals(['castle']);
77 + }
78 +
79 + public function test_entity_permissions_effect_tag_suggestions()
80 + {
81 + $permissionService = $this->app->make(PermissionService::class);
82 +
83 + // Create some tags with similar names to test with and save to a page
84 + $attrs = collect();
85 + $attrs = $attrs->merge(factory(Tag::class, 5)->make(['name' => 'country']));
86 + $attrs = $attrs->merge(factory(Tag::class, 5)->make(['name' => 'color']));
87 + $page = $this->getPageWithTags($attrs);
88 +
89 + $this->asAdmin()->get('/ajax/tags/suggest?search=co')->seeJsonEquals(['color', 'country']);
90 + $this->asEditor()->get('/ajax/tags/suggest?search=co')->seeJsonEquals(['color', 'country']);
91 +
92 + // Set restricted permission the page
93 + $page->restricted = true;
94 + $page->save();
95 + $permissionService->buildJointPermissionsForEntity($page);
96 +
97 + $this->asAdmin()->get('/ajax/tags/suggest?search=co')->seeJsonEquals(['color', 'country']);
98 + $this->asEditor()->get('/ajax/tags/suggest?search=co')->seeJsonEquals([]);
99 + }
100 +
101 + public function test_entity_tag_updating()
102 + {
103 + $page = $this->getPageWithTags();
104 +
105 + $testJsonData = [
106 + ['name' => 'color', 'value' => 'red'],
107 + ['name' => 'color', 'value' => ' blue '],
108 + ['name' => 'city', 'value' => 'London '],
109 + ['name' => 'country', 'value' => ' England'],
110 + ];
111 + $testResponseJsonData = [
112 + ['name' => 'color', 'value' => 'red'],
113 + ['name' => 'color', 'value' => 'blue'],
114 + ['name' => 'city', 'value' => 'London'],
115 + ['name' => 'country', 'value' => 'England'],
116 + ];
117 +
118 + // Do update request
119 + $this->asAdmin()->json("POST", "/ajax/tags/update/page/" . $page->id, ['tags' => $testJsonData]);
120 + $updateData = json_decode($this->response->getContent());
121 + // Check data is correct
122 + $testDataCorrect = true;
123 + foreach ($updateData->tags as $data) {
124 + $testItem = ['name' => $data->name, 'value' => $data->value];
125 + if (!in_array($testItem, $testResponseJsonData)) $testDataCorrect = false;
126 + }
127 + $testMessage = "Expected data was not found in the response.\nExpected Data: %s\nRecieved Data: %s";
128 + $this->assertTrue($testDataCorrect, sprintf($testMessage, json_encode($testResponseJsonData), json_encode($updateData)));
129 + $this->assertTrue(isset($updateData->message), "No message returned in tag update response");
130 +
131 + // Do get request
132 + $this->asAdmin()->get("/ajax/tags/get/page/" . $page->id);
133 + $getResponseData = json_decode($this->response->getContent());
134 + // Check counts
135 + $this->assertTrue(count($getResponseData) === count($testJsonData), "The received tag count is incorrect");
136 + // Check data is correct
137 + $testDataCorrect = true;
138 + foreach ($getResponseData as $data) {
139 + $testItem = ['name' => $data->name, 'value' => $data->value];
140 + if (!in_array($testItem, $testResponseJsonData)) $testDataCorrect = false;
141 + }
142 + $testMessage = "Expected data was not found in the response.\nExpected Data: %s\nRecieved Data: %s";
143 + $this->assertTrue($testDataCorrect, sprintf($testMessage, json_encode($testResponseJsonData), json_encode($getResponseData)));
144 + }
145 +
146 +}
...@@ -9,7 +9,7 @@ class RestrictionsTest extends TestCase ...@@ -9,7 +9,7 @@ class RestrictionsTest extends TestCase
9 public function setUp() 9 public function setUp()
10 { 10 {
11 parent::setUp(); 11 parent::setUp();
12 - $this->user = $this->getNewUser(); 12 + $this->user = $this->getEditor();
13 $this->viewer = $this->getViewer(); 13 $this->viewer = $this->getViewer();
14 $this->restrictionService = $this->app[\BookStack\Services\PermissionService::class]; 14 $this->restrictionService = $this->app[\BookStack\Services\PermissionService::class];
15 } 15 }
......
...@@ -14,7 +14,10 @@ class TestCase extends Illuminate\Foundation\Testing\TestCase ...@@ -14,7 +14,10 @@ class TestCase extends Illuminate\Foundation\Testing\TestCase
14 * @var string 14 * @var string
15 */ 15 */
16 protected $baseUrl = 'http://localhost'; 16 protected $baseUrl = 'http://localhost';
17 +
18 + // Local user instances
17 private $admin; 19 private $admin;
20 + private $editor;
18 21
19 /** 22 /**
20 * Creates the application. 23 * Creates the application.
...@@ -30,6 +33,10 @@ class TestCase extends Illuminate\Foundation\Testing\TestCase ...@@ -30,6 +33,10 @@ class TestCase extends Illuminate\Foundation\Testing\TestCase
30 return $app; 33 return $app;
31 } 34 }
32 35
36 + /**
37 + * Set the current user context to be an admin.
38 + * @return $this
39 + */
33 public function asAdmin() 40 public function asAdmin()
34 { 41 {
35 if($this->admin === null) { 42 if($this->admin === null) {
...@@ -40,6 +47,18 @@ class TestCase extends Illuminate\Foundation\Testing\TestCase ...@@ -40,6 +47,18 @@ class TestCase extends Illuminate\Foundation\Testing\TestCase
40 } 47 }
41 48
42 /** 49 /**
50 + * Set the current editor context to be an editor.
51 + * @return $this
52 + */
53 + public function asEditor()
54 + {
55 + if($this->editor === null) {
56 + $this->editor = $this->getEditor();
57 + }
58 + return $this->actingAs($this->editor);
59 + }
60 +
61 + /**
43 * Quickly sets an array of settings. 62 * Quickly sets an array of settings.
44 * @param $settingsArray 63 * @param $settingsArray
45 */ 64 */
...@@ -79,7 +98,7 @@ class TestCase extends Illuminate\Foundation\Testing\TestCase ...@@ -79,7 +98,7 @@ class TestCase extends Illuminate\Foundation\Testing\TestCase
79 * @param array $attributes 98 * @param array $attributes
80 * @return mixed 99 * @return mixed
81 */ 100 */
82 - protected function getNewUser($attributes = []) 101 + protected function getEditor($attributes = [])
83 { 102 {
84 $user = factory(\BookStack\User::class)->create($attributes); 103 $user = factory(\BookStack\User::class)->create($attributes);
85 $role = \BookStack\Role::getRole('editor'); 104 $role = \BookStack\Role::getRole('editor');
......
...@@ -33,7 +33,7 @@ class UserProfileTest extends TestCase ...@@ -33,7 +33,7 @@ class UserProfileTest extends TestCase
33 33
34 public function test_profile_page_shows_created_content_counts() 34 public function test_profile_page_shows_created_content_counts()
35 { 35 {
36 - $newUser = $this->getNewUser(); 36 + $newUser = $this->getEditor();
37 37
38 $this->asAdmin()->visit('/user/' . $newUser->id) 38 $this->asAdmin()->visit('/user/' . $newUser->id)
39 ->see($newUser->name) 39 ->see($newUser->name)
...@@ -52,7 +52,7 @@ class UserProfileTest extends TestCase ...@@ -52,7 +52,7 @@ class UserProfileTest extends TestCase
52 52
53 public function test_profile_page_shows_recent_activity() 53 public function test_profile_page_shows_recent_activity()
54 { 54 {
55 - $newUser = $this->getNewUser(); 55 + $newUser = $this->getEditor();
56 $this->actingAs($newUser); 56 $this->actingAs($newUser);
57 $entities = $this->createEntityChainBelongingToUser($newUser, $newUser); 57 $entities = $this->createEntityChainBelongingToUser($newUser, $newUser);
58 Activity::add($entities['book'], 'book_update', $entities['book']->id); 58 Activity::add($entities['book'], 'book_update', $entities['book']->id);
...@@ -66,7 +66,7 @@ class UserProfileTest extends TestCase ...@@ -66,7 +66,7 @@ class UserProfileTest extends TestCase
66 66
67 public function test_clicking_user_name_in_activity_leads_to_profile_page() 67 public function test_clicking_user_name_in_activity_leads_to_profile_page()
68 { 68 {
69 - $newUser = $this->getNewUser(); 69 + $newUser = $this->getEditor();
70 $this->actingAs($newUser); 70 $this->actingAs($newUser);
71 $entities = $this->createEntityChainBelongingToUser($newUser, $newUser); 71 $entities = $this->createEntityChainBelongingToUser($newUser, $newUser);
72 Activity::add($entities['book'], 'book_update', $entities['book']->id); 72 Activity::add($entities['book'], 'book_update', $entities['book']->id);
......