book_access.module in Book access 1.x
Same filename and directory in other branches
File
book_access.moduleView source
<?php
/**
* @file
*/
use Drupal\user\UserInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\node\NodeInterface;
use Drupal\Core\Entity\EntityInterface;
/**
* Implements hook_ENTITY_TYPE_insert() for user_role.
*
* Makes sure to set default visibility when a new role is created.
*/
function book_access_user_role_insert(EntityInterface $entity) {
/** @var \Drupal\user\RoleInterface $role */
$role = $entity;
/** @var \Drupal\book_access\BookAccessHelper $book_helper */
$book_helper = \Drupal::service('book_access.book_access_helper');
$book_helper
->setDefaultForRole($role);
}
/**
* Implements hook_node_insert().
*
* Specifically targets creation of book nodes to set some default permissions.
*/
function book_access_node_insert(NodeInterface $node) {
/* if (isset( $node->book['bid'])
&& $node->book['bid']
&& $node->id() == $node->book['bid']) {
// @FIXME
// Could not extract the default value because it is either indeterminate, or
// not scalar. You'll need to provide a default value in
// config/install/book_access.settings.yml and config/schema/book_access.schema.yml.
// @FIXME
// Could not extract the default value because it is either indeterminate, or
// not scalar. You'll need to provide a default value in
// config/install/book_access.settings.yml and config/schema/book_access.schema.yml.
BookAccess::setAuthorGrants(
$node->book['bid'],
$node->getOwnerId(),
array_combine($node->getOwnerId() == 0 ? BookAccess::defaultGrants() : \Drupal::config('book_access.settings')->get("book_access_default_author_access"), $node->getOwnerId() == 0 ? BookAccess::defaultGrants() : \Drupal::config('book_access.settings')->get("book_access_default_author_access"))
);
$roles = user_roles();
$rids = array_keys( $roles);
foreach ($rids as $rid) {
// @FIXME
// // @FIXME
// // The correct configuration object could not be determined. You'll need to
// // rewrite this call manually.
// $roleDefaults = variable_get( "book_access_default_role_{$rid}_access", array());
foreach ($roleDefaults as $default) {
$roleGrants[$default][$rid] = TRUE;
}
}
BookAccess::setRoleGrants( $node->book['bid'], $rids, $roleGrants);
}*/
}
/**
* Implements hook_node_update().
*
* Makes sure defaults propagate to pages that have been 'upgraded' to a book.
*/
function book_access_node_update(NodeInterface $node) {
/* if (isset($node->book['bid']) && $node->book['bid']) {
// Check for existing permissions
// $rowCount = \Drupal::database()->select('book_access_author', 'book_access_author')
// ->condition( 'nid', $node->book['bid'], '=')
// ->condition( 'uid', $node->getOwnerId())
// ->countQuery()
// ->execute()
// ->fetchField();
if ($rowCount == 0) {
// @FIXME
// Could not extract the default value because it is either indeterminate, or
// not scalar. You'll need to provide a default value in
// config/install/book_access.settings.yml and config/schema/book_access.schema.yml.
// @FIXME
// Could not extract the default value because it is either indeterminate, or
// not scalar. You'll need to provide a default value in
// config/install/book_access.settings.yml and config/schema/book_access.schema.yml.
// BookAccess::setAuthorGrants(
// $node->book['bid'],
// $node->getOwnerId(),
// array_combine($node->getOwnerId() == 0 ? BookAccess::defaultGrants() : \Drupal::config('book_access.settings')->get("book_access_default_author_access"), $node->getOwnerId() == 0 ? BookAccess::defaultGrants() : \Drupal::config('book_access.settings')->get("book_access_default_author_access"))
// );
}
$roles = user_roles();
$rids = array_keys($roles);
$roleResultSet = \Drupal::database()->select('book_access_role', 'book_access_role')
->condition('nid', $node->book['bid'], '=')
->condition('rid', $rids, 'IN')
->fields('book_access_role', ['rid'])
->distinct()
->execute();
if ($roleResultSet->rowCount() < count($rids)) {
// Fill in the missing ones.
$existingRids = [];
foreach ($roleResultSet as $row) {
$existingRids[] = $row->rid;
}
$missingRids = array_diff($rids, $existingRids);
foreach ($missingRids as $rid) {
// @FIXME
// // @FIXME
// // The correct configuration object could not be determined. You'll need to
// // rewrite this call manually.
// $defaultToUse = variable_get( "book_access_role_{$rid}_default");
if ($defaultToUse !== NULL) {
$roleDefaults = [];
foreach ($defaultToUse as $grant) {
$roleDefaults[$grant] = $rid;
}
// BookAccess::addRoleGrants( $node->book['bid'], array($rid), $roleDefaults);.
}
}
}
}*/
}
/**
* Implements hook_form_alter().
*
* @see book_outline_form()
* @see book_access_outline_form_submit()
* @see book_access_edit_form_submit()
*/
function book_access_form_alter(&$form, FormStateInterface &$form_state, $form_id) {
/* @var \Drupal\book_access\BookAccessHelper $bookAccessHelper */
$bookAccessHelper = \Drupal::service('book_access.book_access_helper');
if (isset($form['type']) && isset($form['#node']) && $form['type']['#value'] . '_node_form' == $form_id) {
if (isset($form['book']['bid']['#options'])) {
// BookAccess::restrictOptions($form['book']['bid']['#options']);.
}
$form['#submit'][] = 'book_access_edit_form_submit';
}
elseif ($form_id == 'book_outline_form') {
if (isset($form['book']['bid']['#options'])) {
// BookAccess::restrictOptions($form['book']['bid']['#options']);.
}
$form['#submit'][] = 'book_access_outline_form_submit';
if (isset($form['remove'])) {
$form['remove']['#submit'][] = 'book_access_edit_form_submit';
}
}
elseif ($form_id == 'book_admin_settings') {
$form['bad_fs'] = [
'#type' => 'fieldset',
'#title' => t('Book Access Settings'),
'#description' => t('These are the default access rules for authors and roles. Users can only be specified on a per-book basis.'),
];
$form['bad_fs']['book_access_defaults'] = [
'#type' => 'table',
'#caption' => t('Warning: these defaults only apply to books that have yet to be created. Books that already exist must be manually changed.'),
'#header' => [
t('Access Type'),
t('View Book'),
t('Edit Pages'),
t('Delete Pages'),
t('Administer Access'),
t('Add Child Pages'),
t('Edit Book Outlines'),
],
];
$author_defaults = $bookAccessHelper
->getAuthorBookAccessDefaults();
$grants = $author_defaults
->getGrants();
$form['bad_fs']['book_access_defaults']['book_access_author_defaults'] = [
'book_access_author_defaults_access_type' => [
'#markup' => t("Default author's access"),
],
];
foreach ($grants as $grant_type => $grant) {
$form['bad_fs']['book_access_defaults']['book_access_author_defaults'][$grant_type] = [
'#type' => 'checkbox',
'#title' => t('Author %grant_type', [
'%grant_type' => $grant_type,
]),
'#title_display' => 'invisible',
'#default_value' => $grant,
];
}
$role_defaults = $bookAccessHelper
->getRoleBookAccessDefaults();
foreach ($role_defaults as $id => $role_default) {
$grants = $role_default['default_grants']
->getGrants();
$form['bad_fs']['book_access_defaults'][$id] = [
"{$id}_access_type" => [
'#markup' => t("Default access for %role", [
'%role' => $role_default['label'],
]),
],
];
foreach ($grants as $grant_type => $grant) {
$form['bad_fs']['book_access_defaults'][$id][$grant_type] = [
'#type' => 'checkbox',
'#title' => t('%role_label %grant_type', [
'%role_label' => $role_default['label'],
'%grant_type' => $grant_type,
]),
'#title_display' => 'invisible',
'#default_value' => $grant,
];
}
}
$form['#submit'][] = 'book_access_admin_settings_submit';
}
}
/**
* Submit handler for book_admin_settings form.
*
* @param array $form
* @param \Drupal\Core\Form\FormStateInterface $form_state
*/
function book_access_admin_settings_submit(array $form, FormStateInterface $form_state) {
if ($form['#id'] == 'book-admin-settings' && $form_state
->hasValue('book_access_defaults')) {
$bookAccessHelper = \Drupal::service('book_access.book_access_helper');
$bookAccessHelper
->updateDefaultsSettings($form_state
->getValue('book_access_defaults'));
\Drupal::messenger()
->addMessage(t('Saved book access defaults.'));
}
}
/**
* @FIXME
* hook_menu_alter() is gone in Drupal 8. You will have to port its
* functionality manually. The are several mechanisms for this:
*
* To alter routes, you must implement a route subscriber class. An empty one
* has been generated for you in src/Routing/RouteSubscriber.php.
*
* To alter menu link definitions, see hook_menu_links_discovered_alter(). An
* empty implementation has been created at the end of this file.
*
* To alter local task definitions, see hook_menu_local_tasks_alter(). An
* empty implementation has been created for you at the end of this file.
*
* To alter local actions, see hook_menu_local_actions_alter(). An
* empty implementation has been created for you at the end of this file.
*
* Contextual links are altered during rendering only. See
* hook_contextual_links_view_alter(). An empty implementation has been
* created for you at the end of this file.
*
* @see https://www.drupal.org/node/2118147#alter
* @see https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Menu%21menu.api.php/function/hook_menu_links_discovered_alter/8
* @see https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Menu%21menu.api.php/function/hook_menu_local_tasks_alter/8
* @see https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Menu%21menu.api.php/function/hook_menu_local_actions_alter/8
* @see https://api.drupal.org/api/drupal/core%21modules%21contextual%21contextual.api.php/function/hook_contextual_links_view_alter/8
*/
function book_access_menu_alter(&$items) {
/* if (isset($items['node/%node/outline'])) {
$items['node/%node/outline']['access callback'] = '_book_access_outline_access';
}
if (isset($items['node/%node/outline/remove'])) {
$items['node/%node/outline/remove']['access callback'] = '_book_access_outline_remove_access';
}*/
}
/**
* Implements hook_node_delete().
*/
function book_access_node_delete(NodeInterface $node) {
// BookAccess::deleteGrants($node->id());
}
/**
* Implements hook_node_grants().
*/
function book_access_node_grants(AccountInterface $account, $op) {
/* $grants = array();
$grants['book_access_author'] = array($account->uid);
$grants['book_access_role'] = array_keys($account->roles);
$grants['book_access_user'] = array($account->uid);
return $grants;*/
}
/**
* Implements hook_node_view_alter().
*
* Enables the link "Add child page" only for users who have the right
* permission.
*/
function book_access_node_view_alter(&$build) {
if (!empty($node->book['bid']) && !empty($build['links']['book']['#links'])) {
$links = $build['links']['book']['#links'];
$node = $build['#node'];
if (\Drupal::currentUser()
->hasPermission('administer nodes')) {
return;
}
if (!empty($links['book_add_child'])) {
// @FIXME
// // @FIXME
// // This looks like another module's variable. You'll need to rewrite this call
// // to ensure that it uses the correct configuration object.
// $bool = (
// (
// (
// \Drupal::currentUser()->hasPermission('add content to books') &&
// BookAccess::checkGrant($node->book['bid'], 'add_child')
// ) ||
// \Drupal::currentUser()->hasPermission('administer book outlines')
// ) &&
// node_access('create', variable_get('book_child_type', 'book')) &&
// ($node->status == 1) &&
// ($node->book['depth'] < MENU_MAX_DEPTH)
// );
// if (!$bool) {
// unset($links['book_add_child']);
// }
}
}
}
/**
* Implements hook_node_access_explain().
*
* Hook_node_access_explain() is defined in devel_node_access.module, which
* helps you to figure out how node access works and what permissions are
* currently granted.
*/
function book_access_node_access_explain($row) {
/* static $roles = NULL;
$result = array();
if ($row->realm == 'book_access_author') {
$result = array(
t('Grants for book authors')
);
}
elseif ($row->realm == 'book_access_role') {
if (!isset($roles)) {
$roles = user_roles();
}
if (isset($roles[$row->gid])) {
$result = array(
t('Grants for users of role %role',
array('%role' => $roles[$row->gid])
)
);
}
else {
$result = array(
t('Unknown group ID %gid',
array('%gid' => $row->gid)
)
);
}
}
elseif ($row->realm == 'book_access_user') {
if ($user = \Drupal::entityTypeManager()->getStorage('user')->load($row->gid)) {
$result = array(
t('Grants for user %username',
array('%username' => $user->name)
)
);
}
else {
$result = array(
t('Unknown user ID %gid',
array('%gid' => $row->gid)
)
);
}
}
return $result;*/
}
/**
* Implements hook_node_access_records().
*
* Returns a list of grant records for the book node object passed as argument.
* If we have a book child page, we return the access settings of the top level
* parent book page node.
*/
function book_access_node_access_records(NodeInterface $node) {
/* $grants = array();
if (!empty($node->book['bid'])) {
$grants = BookAccess::getGrantRecords($node->book['bid']);
if (is_array($grants) && !$node->isPublished()) {
// unpublished node, grant_view should be off for all types (author,role,user)
foreach ($grants as &$grant) {
$grant['grant_view'] = 0;
}
}
}
return $grants;*/
}
/**
* Implements hook_user_delete().
*/
function book_access_user_delete(UserInterface $account) {
// BookAccess::deleteGrants($account->id(), 'uid');.
}
/**
* Implements hook_node_view().
*
* We want to hide the "Add Child Page" link if the current user
* doesn't have permission for it.
*/
function book_access_node_view(array &$build, NodeInterface $node, $view_mode, $langcode) {
/* if (isset($node->content['links']['book'])
&& isset($node->content['links']['book']['#links']['book_add_child'])) {
if (! BookAccess::checkGrant($node->book['bid'], 'grant_add_child')) {
unset($node->content['links']['book']['#links']['book_add_child']);
}
}*/
}
/**
* Form submission callback for node_form(), and book_outline_form().
*
* @see node_form()
* @see book_outline_form()
* @see book_access_form_alter()
*/
function book_access_edit_form_submit($form, &$form_state) {
// BookAccess::writeGrantRecords($form['#node']);.
}
/**
* Form submission callback for book_outline_form().
*
* @see book_outline_form()
* @see book_access_form_alter()
*/
function book_access_outline_form_submit($form, &$form_state) {
/* if (isset($form['plid']) && $form['plid'] != $form_state['values']['plid']) {
BookAccess::writeGrantRecords($form['#node']);
}*/
}
/**
* Implements hook_menu_links_discovered_alter().
*/
function book_access_menu_links_discovered_alter(array &$links) {
}
/**
* Implements hook_menu_local_tasks_alter().
*/
function book_access_menu_local_tasks_alter(array &$data, $route_name) {
}
/**
* Implements hook_menu_local_actions_alter().
*/
function book_access_menu_local_actions_alter(array &$local_actions) {
}
/**
* Implements hook_contextual_links_view_alter().
*/
function book_access_contextual_links_view_alter(array &$element, array $items) {
}