]> BookStack Code Mirror - bookstack/commitdiff
Merge pull request #10 from BookStackApp/master
authorAbijeet Patro <redacted>
Tue, 2 May 2017 20:11:08 +0000 (01:41 +0530)
committerGitHub <redacted>
Tue, 2 May 2017 20:11:08 +0000 (01:41 +0530)
Latest changes

1  2 
app/Services/PermissionService.php
config/app.php
resources/assets/js/directives.js
resources/lang/en/entities.php

index cb0b68026a7de99e8ec16aaf41b2b4a566ad9ecd,a1b661533a65df232a3b29987e8e7edfb6d13189..c86ef0e7aa51354d375203727a34e9e9abdfbf32
@@@ -3,6 -3,7 +3,7 @@@
  use BookStack\Book;
  use BookStack\Chapter;
  use BookStack\Entity;
+ use BookStack\EntityPermission;
  use BookStack\JointPermission;
  use BookStack\Ownable;
  use BookStack\Page;
@@@ -10,6 -11,7 +11,7 @@@ use BookStack\Role
  use BookStack\User;
  use Illuminate\Database\Connection;
  use Illuminate\Database\Eloquent\Builder;
+ use Illuminate\Database\Query\Builder as QueryBuilder;
  use Illuminate\Support\Collection;
  
  class PermissionService
  
      protected $jointPermission;
      protected $role;
+     protected $entityPermission;
  
      protected $entityCache;
  
      /**
       * PermissionService constructor.
       * @param JointPermission $jointPermission
+      * @param EntityPermission $entityPermission
       * @param Connection $db
       * @param Book $book
       * @param Chapter $chapter
       * @param Page $page
       * @param Role $role
       */
-     public function __construct(JointPermission $jointPermission, Connection $db, Book $book, Chapter $chapter, Page $page, Role $role)
+     public function __construct(JointPermission $jointPermission, EntityPermission $entityPermission, Connection $db, Book $book, Chapter $chapter, Page $page, Role $role)
      {
          $this->db = $db;
          $this->jointPermission = $jointPermission;
+         $this->entityPermission = $entityPermission;
          $this->role = $role;
          $this->book = $book;
          $this->chapter = $chapter;
          // TODO - Update so admin still goes through filters
      }
  
+     /**
+      * Set the database connection
+      * @param Connection $connection
+      */
+     public function setConnection(Connection $connection)
+     {
+         $this->db = $connection;
+     }
      /**
       * Prepare the local entity cache and ensure it's empty
       */
          $this->readyEntityCache();
  
          // Get all roles (Should be the most limited dimension)
-         $roles = $this->role->with('permissions')->get();
+         $roles = $this->role->with('permissions')->get()->all();
  
          // Chunk through all books
-         $this->book->with('permissions')->chunk(500, function ($books) use ($roles) {
-             $this->createManyJointPermissions($books, $roles);
+         $this->bookFetchQuery()->chunk(5, function ($books) use ($roles) {
+             $this->buildJointPermissionsForBooks($books, $roles);
          });
+     }
  
-         // Chunk through all chapters
-         $this->chapter->with('book', 'permissions')->chunk(500, function ($chapters) use ($roles) {
-             $this->createManyJointPermissions($chapters, $roles);
-         });
+     /**
+      * Get a query for fetching a book with it's children.
+      * @return QueryBuilder
+      */
+     protected function bookFetchQuery()
+     {
+         return $this->book->newQuery()->select(['id', 'restricted', 'created_by'])->with(['chapters' => function($query) {
+             $query->select(['id', 'restricted', 'created_by', 'book_id']);
+         }, 'pages'  => function($query) {
+             $query->select(['id', 'restricted', 'created_by', 'book_id', 'chapter_id']);
+         }]);
+     }
  
-         // Chunk through all pages
-         $this->page->with('book', 'chapter', 'permissions')->chunk(500, function ($pages) use ($roles) {
-             $this->createManyJointPermissions($pages, $roles);
-         });
+     /**
+      * Build joint permissions for an array of books
+      * @param Collection $books
+      * @param array $roles
+      * @param bool $deleteOld
+      */
+     protected function buildJointPermissionsForBooks($books, $roles, $deleteOld = false) {
+         $entities = clone $books;
+         /** @var Book $book */
+         foreach ($books->all() as $book) {
+             foreach ($book->getRelation('chapters') as $chapter) {
+                 $entities->push($chapter);
+             }
+             foreach ($book->getRelation('pages') as $page) {
+                 $entities->push($page);
+             }
+         }
+         if ($deleteOld) $this->deleteManyJointPermissionsForEntities($entities->all());
+         $this->createManyJointPermissions($entities, $roles);
      }
  
      /**
       */
      public function buildJointPermissionsForEntity(Entity $entity)
      {
-         $roles = $this->role->get();
-         $entities = collect([$entity]);
+         $entities = [$entity];
          if ($entity->isA('book')) {
-             $entities = $entities->merge($entity->chapters);
-             $entities = $entities->merge($entity->pages);
-         } elseif ($entity->isA('chapter')) {
-             $entities = $entities->merge($entity->pages);
+             $books = $this->bookFetchQuery()->where('id', '=', $entity->id)->get();
+             $this->buildJointPermissionsForBooks($books, $this->role->newQuery()->get(), true);
+             return;
          }
  
+         $entities[] = $entity->book;
+         if ($entity->isA('page') && $entity->chapter_id) $entities[] = $entity->chapter;
+         if ($entity->isA('chapter')) {
+             foreach ($entity->pages as $page) {
+                 $entities[] = $page;
+             }
+         }
          $this->deleteManyJointPermissionsForEntities($entities);
-         $this->createManyJointPermissions($entities, $roles);
+         $this->buildJointPermissionsForEntities(collect($entities));
      }
  
      /**
       */
      public function buildJointPermissionsForEntities(Collection $entities)
      {
-         $roles = $this->role->get();
-         $this->deleteManyJointPermissionsForEntities($entities);
+         $roles = $this->role->newQuery()->get();
+         $this->deleteManyJointPermissionsForEntities($entities->all());
          $this->createManyJointPermissions($entities, $roles);
      }
  
       */
      public function buildJointPermissionForRole(Role $role)
      {
-         $roles = collect([$role]);
+         $roles = [$role];
          $this->deleteManyJointPermissionsForRoles($roles);
  
          // Chunk through all books
-         $this->book->with('permissions')->chunk(500, function ($books) use ($roles) {
-             $this->createManyJointPermissions($books, $roles);
-         });
-         // Chunk through all chapters
-         $this->chapter->with('book', 'permissions')->chunk(500, function ($books) use ($roles) {
-             $this->createManyJointPermissions($books, $roles);
-         });
-         // Chunk through all pages
-         $this->page->with('book', 'chapter', 'permissions')->chunk(500, function ($books) use ($roles) {
-             $this->createManyJointPermissions($books, $roles);
+         $this->bookFetchQuery()->chunk(5, function ($books) use ($roles) {
+             $this->buildJointPermissionsForBooks($books, $roles);
          });
      }
  
       */
      protected function deleteManyJointPermissionsForRoles($roles)
      {
-         foreach ($roles as $role) {
-             $role->jointPermissions()->delete();
-         }
+         $roleIds = array_map(function($role) {
+             return $role->id;
+         }, $roles);
+         $this->jointPermission->newQuery()->whereIn('id', $roleIds)->delete();
      }
  
      /**
      protected function deleteManyJointPermissionsForEntities($entities)
      {
          if (count($entities) === 0) return;
-         $query = $this->jointPermission->newQuery();
-             foreach ($entities as $entity) {
-                 $query->orWhere(function($query) use ($entity) {
-                     $query->where('entity_id', '=', $entity->id)
-                         ->where('entity_type', '=', $entity->getMorphClass());
-                 });
+         $this->db->transaction(function() use ($entities) {
+             foreach (array_chunk($entities, 1000) as $entityChunk) {
+                 $query = $this->db->table('joint_permissions');
+                 foreach ($entityChunk as $entity) {
+                     $query->orWhere(function(QueryBuilder $query) use ($entity) {
+                         $query->where('entity_id', '=', $entity->id)
+                             ->where('entity_type', '=', $entity->getMorphClass());
+                     });
+                 }
+                 $query->delete();
              }
-         $query->delete();
+         });
      }
  
      /**
       * Create & Save entity jointPermissions for many entities and jointPermissions.
       * @param Collection $entities
-      * @param Collection $roles
+      * @param array $roles
       */
      protected function createManyJointPermissions($entities, $roles)
      {
          $this->readyEntityCache();
          $jointPermissions = [];
+         // Fetch Entity Permissions and create a mapping of entity restricted statuses
+         $entityRestrictedMap = [];
+         $permissionFetch = $this->entityPermission->newQuery();
+         foreach ($entities as $entity) {
+             $entityRestrictedMap[$entity->getMorphClass() . ':' . $entity->id] = boolval($entity->getRawAttribute('restricted'));
+             $permissionFetch->orWhere(function($query) use ($entity) {
+                 $query->where('restrictable_id', '=', $entity->id)->where('restrictable_type', '=', $entity->getMorphClass());
+             });
+         }
+         $permissions = $permissionFetch->get();
+         // Create a mapping of explicit entity permissions
+         $permissionMap = [];
+         foreach ($permissions as $permission) {
+             $key = $permission->restrictable_type . ':' . $permission->restrictable_id . ':' . $permission->role_id . ':' . $permission->action;
+             $isRestricted = $entityRestrictedMap[$permission->restrictable_type . ':' . $permission->restrictable_id];
+             $permissionMap[$key] = $isRestricted;
+         }
+         // Create a mapping of role permissions
+         $rolePermissionMap = [];
+         foreach ($roles as $role) {
+             foreach ($role->getRelationValue('permissions') as $permission) {
+                 $rolePermissionMap[$role->getRawAttribute('id') . ':' . $permission->getRawAttribute('name')] = true;
+             }
+         }
+         // Create Joint Permission Data
          foreach ($entities as $entity) {
              foreach ($roles as $role) {
                  foreach ($this->getActions($entity) as $action) {
-                     $jointPermissions[] = $this->createJointPermissionData($entity, $role, $action);
+                     $jointPermissions[] = $this->createJointPermissionData($entity, $role, $action, $permissionMap, $rolePermissionMap);
                  }
              }
          }
-         $this->jointPermission->insert($jointPermissions);
+         $this->db->transaction(function() use ($jointPermissions) {
+             foreach (array_chunk($jointPermissions, 1000) as $jointPermissionChunk) {
+                 $this->db->table('joint_permissions')->insert($jointPermissionChunk);
+             }
+         });
      }
  
  
      /**
       * Get the actions related to an entity.
-      * @param $entity
+      * @param Entity $entity
       * @return array
       */
-     protected function getActions($entity)
+     protected function getActions(Entity $entity)
      {
          $baseActions = ['view', 'update', 'delete'];
-         if ($entity->isA('chapter')) {
-             $baseActions[] = 'page-create';
-         } else if ($entity->isA('book')) {
-             $baseActions[] = 'page-create';
-             $baseActions[] = 'chapter-create';
-         }
-          return $baseActions;
+         if ($entity->isA('chapter') || $entity->isA('book')) $baseActions[] = 'page-create';
+         if ($entity->isA('book')) $baseActions[] = 'chapter-create';
+         return $baseActions;
      }
  
      /**
       * for a particular action.
       * @param Entity $entity
       * @param Role $role
-      * @param $action
+      * @param string $action
+      * @param array $permissionMap
+      * @param array $rolePermissionMap
       * @return array
       */
-     protected function createJointPermissionData(Entity $entity, Role $role, $action)
+     protected function createJointPermissionData(Entity $entity, Role $role, $action, $permissionMap, $rolePermissionMap)
      {
          $permissionPrefix = (strpos($action, '-') === false ? ($entity->getType() . '-') : '') . $action;
-         $roleHasPermission = $role->hasPermission($permissionPrefix . '-all');
-         $roleHasPermissionOwn = $role->hasPermission($permissionPrefix . '-own');
+         $roleHasPermission = isset($rolePermissionMap[$role->getRawAttribute('id') . ':' . $permissionPrefix . '-all']);
+         $roleHasPermissionOwn = isset($rolePermissionMap[$role->getRawAttribute('id') . ':' . $permissionPrefix . '-own']);
          $explodedAction = explode('-', $action);
          $restrictionAction = end($explodedAction);
  
              return $this->createJointPermissionDataArray($entity, $role, $action, true, true);
          }
  
-         if ($entity->isA('book')) {
-             if (!$entity->restricted) {
-                 return $this->createJointPermissionDataArray($entity, $role, $action, $roleHasPermission, $roleHasPermissionOwn);
-             } else {
-                 $hasAccess = $entity->hasActiveRestriction($role->id, $restrictionAction);
-                 return $this->createJointPermissionDataArray($entity, $role, $action, $hasAccess, $hasAccess);
-             }
+         if ($entity->restricted) {
+             $hasAccess = $this->mapHasActiveRestriction($permissionMap, $entity, $role, $restrictionAction);
+             return $this->createJointPermissionDataArray($entity, $role, $action, $hasAccess, $hasAccess);
+         }
  
-         } elseif ($entity->isA('chapter')) {
+         if ($entity->isA('book')) {
+             return $this->createJointPermissionDataArray($entity, $role, $action, $roleHasPermission, $roleHasPermissionOwn);
+         }
  
-             if (!$entity->restricted) {
-                 $book = $this->getBook($entity->book_id);
-                 $hasExplicitAccessToBook = $book->hasActiveRestriction($role->id, $restrictionAction);
-                 $hasPermissiveAccessToBook = !$book->restricted;
-                 return $this->createJointPermissionDataArray($entity, $role, $action,
-                     ($hasExplicitAccessToBook || ($roleHasPermission && $hasPermissiveAccessToBook)),
-                     ($hasExplicitAccessToBook || ($roleHasPermissionOwn && $hasPermissiveAccessToBook)));
-             } else {
-                 $hasAccess = $entity->hasActiveRestriction($role->id, $restrictionAction);
-                 return $this->createJointPermissionDataArray($entity, $role, $action, $hasAccess, $hasAccess);
+         // For chapters and pages, Check if explicit permissions are set on the Book.
+         $book = $this->getBook($entity->book_id);
+         $hasExplicitAccessToParents = $this->mapHasActiveRestriction($permissionMap, $book, $role, $restrictionAction);
+         $hasPermissiveAccessToParents = !$book->restricted;
+         // For pages with a chapter, Check if explicit permissions are set on the Chapter
+         if ($entity->isA('page') && $entity->chapter_id !== 0) {
+             $chapter = $this->getChapter($entity->chapter_id);
+             $hasPermissiveAccessToParents = $hasPermissiveAccessToParents && !$chapter->restricted;
+             if ($chapter->restricted) {
+                 $hasExplicitAccessToParents = $this->mapHasActiveRestriction($permissionMap, $chapter, $role, $restrictionAction);
              }
+         }
  
-         } elseif ($entity->isA('page')) {
-             if (!$entity->restricted) {
-                 $book = $this->getBook($entity->book_id);
-                 $hasExplicitAccessToBook = $book->hasActiveRestriction($role->id, $restrictionAction);
-                 $hasPermissiveAccessToBook = !$book->restricted;
-                 $chapter = $this->getChapter($entity->chapter_id);
-                 $hasExplicitAccessToChapter = $chapter && $chapter->hasActiveRestriction($role->id, $restrictionAction);
-                 $hasPermissiveAccessToChapter = $chapter && !$chapter->restricted;
-                 $acknowledgeChapter = ($chapter && $chapter->restricted);
-                 $hasExplicitAccessToParents = $acknowledgeChapter ? $hasExplicitAccessToChapter : $hasExplicitAccessToBook;
-                 $hasPermissiveAccessToParents = $acknowledgeChapter ? $hasPermissiveAccessToChapter : $hasPermissiveAccessToBook;
-                 return $this->createJointPermissionDataArray($entity, $role, $action,
-                     ($hasExplicitAccessToParents || ($roleHasPermission && $hasPermissiveAccessToParents)),
-                     ($hasExplicitAccessToParents || ($roleHasPermissionOwn && $hasPermissiveAccessToParents))
-                 );
-             } else {
-                 $hasAccess = $entity->hasRestriction($role->id, $action);
-                 return $this->createJointPermissionDataArray($entity, $role, $action, $hasAccess, $hasAccess);
-             }
+         return $this->createJointPermissionDataArray($entity, $role, $action,
+             ($hasExplicitAccessToParents || ($roleHasPermission && $hasPermissiveAccessToParents)),
+             ($hasExplicitAccessToParents || ($roleHasPermissionOwn && $hasPermissiveAccessToParents))
+         );
+     }
  
-         }
+     /**
+      * Check for an active restriction in an entity map.
+      * @param $entityMap
+      * @param Entity $entity
+      * @param Role $role
+      * @param $action
+      * @return bool
+      */
+     protected function mapHasActiveRestriction($entityMap, Entity $entity, Role $role, $action) {
+         $key = $entity->getMorphClass() . ':' . $entity->getRawAttribute('id') . ':' . $role->getRawAttribute('id') . ':' . $action;
+         return isset($entityMap[$key]) ? $entityMap[$key] : false;
      }
  
      /**
       */
      protected function createJointPermissionDataArray(Entity $entity, Role $role, $action, $permissionAll, $permissionOwn)
      {
-         $entityClass = get_class($entity);
          return [
              'role_id'            => $role->getRawAttribute('id'),
              'entity_id'          => $entity->getRawAttribute('id'),
-             'entity_type'        => $entityClass,
+             'entity_type'        => $entity->getMorphClass(),
              'action'             => $action,
              'has_permission'     => $permissionAll,
              'has_permission_own' => $permissionOwn,
          $action = end($explodedPermission);
          $this->currentAction = $action;
  
 -        $nonJointPermissions = ['restrictions', 'image', 'attachment'];
 +        $nonJointPermissions = ['restrictions', 'image', 'attachment', 'comment'];
  
          // Handle non entity specific jointPermissions
          if (in_array($explodedPermission[0], $nonJointPermissions)) {
       * @param integer $book_id
       * @param bool $filterDrafts
       * @param bool $fetchPageContent
-      * @return \Illuminate\Database\Query\Builder
+      * @return QueryBuilder
       */
      public function bookChildrenQuery($book_id, $filterDrafts = false, $fetchPageContent = false) {
          $pageSelect = $this->db->table('pages')->selectRaw($this->page->entityRawQuery($fetchPageContent))->where('book_id', '=', $book_id)->where(function($query) use ($filterDrafts) {
diff --combined config/app.php
index feab6651c3252706473b2abf67d0dc85ed2b3b40,54cdca21bb25893d8c5b85aa4bc78a5eb10aa891..13bb9aa7ddb90d4b08ee8e4bf03fc6e5a7410ede
@@@ -3,7 -3,7 +3,7 @@@
  return [
  
  
 -    'env' => env('APP_ENV', 'production'),
 +    'env' => env('APP_ENV', 'development'),
  
      'editor' => env('APP_EDITOR', 'html'),
  
@@@ -18,7 -18,7 +18,7 @@@
      |
      */
  
 -    'debug' => env('APP_DEBUG', false),
 +    'debug' => env('APP_DEBUG', true),
  
      /*
      |--------------------------------------------------------------------------
@@@ -58,6 -58,7 +58,7 @@@
      */
  
      'locale' => env('APP_LANG', 'en'),
+     'locales' => ['en', 'de', 'es', 'fr', 'nl', 'pt_BR', 'sk'],
  
      /*
      |--------------------------------------------------------------------------
index d119d2e927813d3c6d651bfd1fac9c31b0ef43d6,3219db8f997b294b4246a8bc8d0de4d75651ca3a..cae07a1663cde3aa70024be61287ab1454f20e95
@@@ -215,7 -215,7 +215,7 @@@ module.exports = function (ngApp, event
          }
      }]);
  
-     const md = new MarkdownIt();
+     const md = new MarkdownIt({html: true});
      md.use(mdTasksLists, {label: true});
  
      /**
              }
          };
      }]);
 +
 +
 +    ngApp.directive('simpleMarkdownInput', ['$timeout', function ($timeout) {
 +        return {
 +            restrict: 'A',
 +            scope: {
 +                smdModel: '=',
 +                smdChange: '=',
 +                smdGetContent: '=',
 +                smdClear: '='
 +            },
 +            link: function (scope, element, attrs) {
 +                // Set initial model content
 +                element = element.find('textarea').first();
 +                let simplemde = new SimpleMDE({
 +                    element: element[0],
 +                    status: []
 +                });
 +                let content = element.val();
 +                simplemde.value(content)
 +                scope.smdModel = content;
 +
 +                simplemde.codemirror.on('change', (event) => {
 +                    content = simplemde.value();
 +                    $timeout(() => {
 +                        scope.smdModel = content;
 +                        if (scope.smdChange) {
 +                            scope.smdChange(element, content);
 +                        }
 +                    });
 +                });
 +                
 +                if ('smdGetContent' in attrs) {
 +                    scope.smdGetContent = function () {
 +                        return simplemde.options.previewRender(simplemde.value());
 +                    };
 +                }
 +                
 +                if ('smdClear' in attrs) {
 +                    scope.smdClear = function () {
 +                        simplemde.value('');
 +                        scope.smdModel = '';                        
 +                    };
 +                }
 +            }
 +        }
 +    }]);
 +    
 +    ngApp.directive('commentReply', ['$timeout', function ($timeout) {        
 +        return {
 +            restrict: 'E',
 +            templateUrl: 'comment-reply.html',
 +            scope: {
 +                
 +            },
 +            link: function (scope, element, attr) {
 +               
 +            }
 +        }
 +                
 +    }]);
 +
 +    ngApp.directive('commentReplyLink', ['$document', '$compile', function ($document, $compile) {
 +        return { 
 +            link: function (scope, element, attr) {
 +                element.on('$destroy', function () {
 +                    element.off('click');
 +                    scope.$destroy(); 
 +                });
 +                
 +                element.on('click', function () {
 +                    var $container = element.parents('.comment-box').first();
 +                    if (!$container.length) {
 +                        console.error('commentReplyLink directive should be placed inside a container with class comment-box!');
 +                        return;
 +                    }
 +                    if (attr.noCommentReplyDupe) {
 +                        removeDupe();                    
 +                    }
 +                    var compiledHTML = $compile('<comment-reply></comment-reply>')(scope);
 +                    $container.append(compiledHTML);
 +                });
 +            }
 +        };
 +        
 +        
 +        function removeDupe() {
 +            let $existingElement = $document.find('comment-reply');
 +            if (!$existingElement.length) {
 +                return;
 +            }
 +            
 +            $existingElement.remove();
 +        }
 +    }]);
  };
index ec0e173069a26d986849f0f90fd9047c55e035ba,450f4ce4851bcfb49703fe8e97e039ec1cb0c0aa..11e29976a6f7ab86d091a726c6b85c1d6f26bcb5
@@@ -14,6 -14,7 +14,7 @@@ return 
      'recent_activity' => 'Recent Activity',
      'create_now' => 'Create one now',
      'revisions' => 'Revisions',
+     'meta_revision' => 'Revision #:revisionCount',
      'meta_created' => 'Created :timeLength',
      'meta_created_name' => 'Created :timeLength by :user',
      'meta_updated' => 'Updated :timeLength',
      'pages_revision_named' => 'Page Revision for :pageName',
      'pages_revisions_created_by' => 'Created By',
      'pages_revisions_date' => 'Revision Date',
+     'pages_revisions_number' => '#',
      'pages_revisions_changelog' => 'Changelog',
      'pages_revisions_changes' => 'Changes',
      'pages_revisions_current' => 'Current Version',
      'profile_not_created_pages' => ':userName has not created any pages',
      'profile_not_created_chapters' => ':userName has not created any chapters',
      'profile_not_created_books' => ':userName has not created any books',
 +
 +    /**
 +     * Comments
 +     */
 +    'comment' => 'Comment',
 +    'comments' => 'Comments'
  ];