List of permissions for Drupal8 routing file - symfony

I'm working on custom Drupal8 module. My module uses this routing file:
kalvis.routing.yml
kalvis.content:
path: '/kalvis/{from}/{to}'
defaults:
_controller: '\Drupal\kalvis\Controller\kalvisController::content'
_title: ''
requirements:
_permission: 'access content'
What does _permission part stand for and where can I find a list of all possible values for this parameter?(in tut's I've watched were used only access content and access administrative content but I suppose there is a lot more of them)
PS: I'm using Drupal 8 beta 10 installed on WAMP

If you want to see a list of all permission, the code below should work. work. If you are coding your own module you can define your own permissions and test if a user has a role with that permission.
function my_module_page_attachments_alter(array &$attachments) {
$perms = array_keys(\Drupal::service('user.permissions')->getPermissions());
}

To answer the question what is the _permission part of the routing structure. Here is a quote from the drupal docs about what it does.
_permission: A permission string (e.g., _permission: 'access content'). You can specify multiple permissions by separating them with ',' (comma) (e.g., _permission: 'access content,access user profiles') for AND logic or '+' (plus) for OR logic (e.g., _permission: 'access content+access user profiles' means a visitor needs either the access content permission or the access user profiles permission to view the page. Having both is fine, too.). Module-specific permission strings can be defined in my_module_name.permissions.yml. See hook_permission() replaced with permissions defined in a my_module_name.permissions.yml file for details.
source: https://www.drupal.org/docs/drupal-apis/routing-system/structure-of-routes
To put it simply this restricts access to this route by only allowing users with the specified permission(s) to access it. To use it you need to know the system name of the permission(s) you want to use to restrict access. Then you just place then as a string behind this paramerter. Like in the quote above. You can choose to use multiple permissions by separating them with , for AND logic or + for OR logic. Permissions system names are allowed to have spaces in them and frequently do.
I don't think there is any way to directly see it in ui if you are talking about the system names of the permissions. You can ofcource see all permissions on www.site.com/admin/people/permissions. If you are in a hurry and/or looking for a specific permission you can always look through the module.permissions.yml file of the module this permission is defined in.
If you do want to see all permissions you can make your own list of all the system names.
You can use the PermissionHandler service from the core module.
This does the following gets all yaml's and creates a list.
You would call this by calling Drupal::service('user.permissions')->getPermissions() (https://api.drupal.org/api/drupal/core%21modules%21user%21src%21PermissionHandler.php/function/PermissionHandler%3A%3AgetPermissions/8.2.x)
You can use or try to write similar code to the functionality of the user_role_permissions function from the user.module file in drupal core. It looks like this:
function user_role_permissions(array $roles) {
if (defined('MAINTENANCE_MODE') && MAINTENANCE_MODE == 'update') {
return _user_role_permissions_update($roles);
}
$entities = Role::loadMultiple($roles);
$role_permissions = array();
foreach ($roles as $rid) {
$role_permissions[$rid] = isset($entities[$rid]) ? $entities[$rid]
->getPermissions() : array();
}
return $role_permissions;
}
This code as you can see just loads all the role entities with loadMultiple (although technically you should use the entitytypemanager to load the entities whenever possible like $entities = \Drupal::entityTypeManager()->getStorage($entity_type)->loadMultiple([1, 2, 3]); for more information see the drupal entity api (https://www.drupal.org/docs/drupal-apis/entity-api/working-with-the-entity-api)).
After loading all the roles it makes a list of all permissions.
Source information below. This should stay up to date because drupal keeps their documentation versioned. But because comments suggested it I figured I might as well write it out to save you some clicks.
Original drupal documentation.
https://api.drupal.org/api/drupal/core!modules!user!user.module/function/user_role_permissions/8.2.x
Hope this helps! :)

You can confirm in the page '/admin/people/permissions'.

A quick and dirty way to see them is to create a View with a Page display. Then in the 'Access' section, ensure 'Permission' is selected and open up the options as if you were going to choose a different permission.
You can now inspect the HTML of the <select> element, the Ids of each option is the correct name for each permission:

Related

Drupal user permissions & odd content types

I have a permissions problem in Drupal. I want users to be able to create a certain node type, but there are two different paths I need to give them permissions for to let them do this. The type is content created by a module called isbn2node, and there are two ways to make content through it, each with different paths:
?=node/add/isbn2node-book
?=node/add/isbn2node_book/isbn2node
One has an underscore and the other one has a hyphen. The first path leads to a form that lets users enter information on a book manually; the second path lets them enter an ISBN, searches for it, and populates the form for them based on the results.
I've changed permissions in the People menu so they can add isbn2node-book content manually using the first path, but there isn't an option to let them use the second method. Aliasing the url so it didn't have node/add in the path didn't work either.
Creating a duplicate content type seems like an ugly solution to this; is there a more elegant way to let users access that second path?
A little code in a custom module using hook_node_access should do it.
$node is either a node object or the machine name of the content type on which to perform the access check (if the node is being created then the $node object is not available so it will be a string instead).
So this should do it:
function MY_MODULE_node_access($node, $op, $account) {
if ($op == 'create') {
$type = $node;
if($type == 'book' && $account->uid) return NODE_ACCESS_ALLOW;
}
}
I figured this out, and the issues I was having were specific to this content type. The ISBN2Node module requires users to have the Administer Nodes permission to use its lookup and bulk import features.
There is some extra code for the module's hook_permission and hook_menu sections submitted as a fix in the module's issues thread.

User edits only its own post.Using Plone permisisons

I have a Plone website and create a menu item.
In the sharing tab I add each user that can post a topic.
How can I prevent that user1 edits posts owned by user2? Currently user1 can edit user2 posts.
Previously I try creating a group, assign each user to this group and add the group using the sharing tab, but in this way one user edit posts from another user.
Just subtract (uncheck) the 'Can edit'-permission of the sharing-tab.
The creator of an item is by default also owner, owners have edit-permission, thus users can edit their own items but not the ones of others.
Update (according to the new comment):
To inhibit the add-privilege on subfolders you'll need to break the inheritage of the Contributors-role, to which the 'Can add'-permission is assigned to.
However this seems not to be possible, yet. Quoting Martin Aspeli from his article "Understanding permissions and roles":
"Currently (until Plone 2.1, most likely), local roles can be added at a lower level in the acqusition tree, but not taken away".
So you need to look for another approach and, as Martijn already suggested, you'll most likely want to go with a custom workflow for your - assumingly folderish - contenttype and to all types that should be allowed to add in it (fortunately by default, Images and Files inherit the state of its parent, otherwise you probably have to think of a multi-chained workflow, but that's worth a new post even, or - ugly - create copies of contenttypes only to give them another workflow).
In that case, do as follows:
Create a workflow as adviced in http://developer.plone.org/content/workflow.html (I updated it lately, please let us know, if you have suggestions for improvements or contribute yourself).
Add the 'Add portal content'-permission to your workflow (in ZMI clickon your workflowname andhit the permissions-tab, select it from the dropdown).
For each state in your workflow (click on the state's name), uncheck 'Aquire permission settings', this way you break the inheritage of the Contibutors-role. Then check the 'Add portal content'-permission for each role you want to grant it, which would be at least the Owner-role in your case, and you might also Managers be able to access everything.
Update2:
Another, more challenging but IMHO much better, approach could be:
On your contenttype's inititialization (=your ct's class is called) trigger a script (f.e. with a contentrule/eventhandler/subscriber or in you ct's class-definition, itself), which looks up the inherited sharing-permissions on the parent, blocks them (__ac_local_roles_block__ = True) and reassign all roles again, but the Contributor's one, for the new born object (your folderish contenttype).
This would avoid creating a whole new workflow just to solve this case.
To do this, please read the docs (just updated, comments always welcome), to see how an event-handler is registrated:
http://developer.plone.org/components/events.html?highlight=events#example-register-an-event-handler-on-your-contenttype-s-creation
The executed python-script could contain s.th. like:
from Acquisition import aq_parent
def inhibit_parent_inherited_contributor_role(self, event):
""" Blocks local-roles on freshly created children in our
contenttype and re-assigns all its parent's local-roles but
'Contributor' to the child.
"""
# Block all inherited local-permissions, also of grand-parents:
self.__ac_local_roles_block__ = True
# Get local-roles assigned to parent and only to parent:
parent_roles = self.aq_parent.get_local_roles()
# Iterate over each assigned user and group to get their roles:
for userid, roles in parent_roles:
# Provide a list variable, to collect the new roles:
# of a group or user:
new_roles = []
# Iterate over the user's, respectively group's, roles:
for role in roles:
# Exclude 'Contributor' of new role-list:
if role != u'Contributor':
# Add all other roles to list of new roles:
new_roles.append(role)
# Finally assign new roles to the child for each found user and group:
self.manage_setLocalRoles(userid, new_roles)
Disclaimer:
I have tested this with IObjectEditedEvent, which works fine. Whereas the IObjectAddedEvent is fired four times (why?) and I wasn't able to tame that quickly, but plone.app.contentrules.handlers.py, does :) Have a closer look at it, maybe including a contentrule in the solution can be even better.
For an in-depth code-example about roles, see Andreas Jung's lovely zopyx.plone.cassandra and its computeRoleMap.py .
And I haven't looked at collective.subtractiveworkflow, yet. In case you do, please tell us about it :)
You need to restrict editing to the Owner role if you only want to have users edit their own content.

Modify the title given in hook_menu() from another module

How can I change the title given to the /user/[uid] page from Your account to Welcome [user name] for logged-in user, where [user name] is the username for the currently logged-in user?
Use hook_menu_alter.
Alter the data being saved to the {menu_router} table after hook_menu is invoked.
Code sample:
function MYMODULE_menu_alter()
{
global $user;
if($user->uid != 0)
$items['user']['title'] = 'Welcome ' . $user->name;
}
You should be able to accomplish this with the Menu token module:
Menu Token module provides tokens, that could be used in title or in path of menu items (links).
(It requires the popular Token module.)
Note that with Drupal 7.23, the user.module includes a 'title callback' to determine if the user is logged in or not, and respond with a corresponding title.
Code that worked for me (through theme template, instead of a custom module):
function YOURTHEME_menu_alter(&$items) {
$items['user']['title callback'] = 'YOURTHEME_user_menu_title';
}
function YOURTHEME_user_menu_title() {
global $user;
return user_is_logged_in() ? t($user->name) : t('User account');
}
The String Overrides module should make this easy.
In Drupal 7, hook_menu() and hook_menu_alter() are just invoked when the data about routes implemented from modules needs to be refreshed, for example when a module is enabled, disabled, installed, or uninstalled. An implementation of hook_menu_alter() that uses the name of the currently logged-in user in the title would show the same username for different users.
Differently, the title callback associated with a route is called every time the page associated with that route is rendered.
The correct code would be similar to the following one.
function mymodule_menu_alter(&$items) {
$items['user']['title callback'] = 'mymodule_user_profile_title';
}
function mymodule_user_profile_title() {
global $user;
return user_is_logged_in() ? t('Welcome, #name', array('#name' => format_username($user))) : t('User account');
}
Notice that the first argument of t() needs to be a literal string, not a dynamic value as in t($user->name) because the database table containing the string translations would not contain the translation for every username used in a site.
It is also wrong because the shown username is invariant respect the language used on a site: For example, in an Italian site, a username like Albert isn't translated to Alberto, nor Vincent is translated to Vincenzo.
When showing a username in the UI, it is always preferable to use format_username(), which allows to third-party module to change what shown as username. (For example, a module could show the content of a user field, instead of showing the login username.)
If you aren't willing to write custom code, you could use the String Overrides module. If you don't want to use any module just for changing the title of the user profile page, you could add the following code in the settings.php file used for the site.
$conf['locale_custom_strings_en'][''] = array(
'My account' => 'Welcome to my site'
);
Notice that, either using the String Overrides module or adding the $conf['locale_custom_strings_en'][''] array in the settings.php file, you cannot:
Provide a string that changes basing on the logged-in user (which is what the question is asking for)
Provide a string that is used only on specific pages
The latter case could be a pro or a con. If the string that needs to be changed is generic enough, it would be replaced even when it should not.

How do I list all nodes created by user specified in argument using Views in Drupal?

I have been trying to create a page using views that will list down all the nodes authored by a specific user.
The user name will be specified in the path (like - stuff/[user-name] )
Can someone please tell me how to do this using Views.
I am stuck on a dead end
for the views url path specify: stuff/%
in the arguments section add: user -> user: name
Should do it, but I'm not sure if it isn't buggy (see this issue: http://drupal.org/node/744468)
If you use user:id instead of username, you will be fine.

Drupal - Getting node id from view to customise link in block

How can I build a block in Drupal which is able to show the node ID of the view page the block is currently sitting on?
I'm using views to build a large chunk of my site, but I need to be able to make "intelligent" blocks in PHP mode which will have dynamic content depending on what the view is displaying.
How can I find the $nid which a view is currently displaying?
Here is a more-robust way of getting the node ID:
<?php
// Check that the current URL is for a specific node:
if(arg(0) == 'node' && is_numeric(arg(1))) {
return arg(1); // Return the NID
}
else { // Whatever it is we're looking at, it's not a node
return NULL; // Return an invalid NID
}
?>
This method works even if you have a custom path for your node with the path and/or pathauto modules.
Just for reference, if you don't turn on the path module, the default URLs that Drupal generates are called "system paths" in the documentation. If you do turn on the path module, you are able to set custom paths which are called "aliases" in the documentation.
Since I always have the path module turned on, one thing that confused me at first was whether it was ever possible for the arg function to return part of an alias rather than part of system path.
As it turns out, the arg function will always return a system path because the arg function is based on $_GET['q']... After a bit of research it seems that $_GET['q'] will always return a system path.
If you want to get the path from the actual page request, you need to use $_REQUEST['q']. If the path module is enabled, $_REQUEST['q'] may return either an alias or a system path.
For a solution, especially one that involves a view argument in the midst of a path like department/%/list, see the blog post Node ID as View Argument from SEO-friendly URL Path.
In the end this snippet did the job - it just stripped the clean URL and reported back the very last argument.
<?php
$refer= $_SERVER ['REQUEST_URI'];
$nid = explode("/", $refer);
$nid = $nid[3];
?>
Given the comment reply, the above was probably reduced to this, using the Drupal arg() function to get a part of the request path:
<?php
$nid = arg(3);
?>
You should considder the panels module. It is a very big module and requires some work before you really can tap into it's potential. So take that into considderation.
You can use it to setup a page containing several views/blocks that can be placed in different regions. It uses a concept called context which can be anything related to what you are viewing. You can use that context to determine which node is being viewed and not only change blocks but also layout. It is also a bit more clean since you can move the PHP code away from admin interface.
On a side note, it's also written by the views author.
There are a couple of ways to go about this:
You can make your blocks with Views and pass the nid in through an argument.
You can manually pass in the nid by accessing the $view object using the code below. It's an array at $view->result. Each row in the view is an object in that array, and the nid is in that object for each one. So you could run a foreach on that and get all of the nid of all rows in the view pretty easily.
The first option is a lot easier, so if that suits your needs I would go with that.
New about Drupal 7: The correct way to get the node id is using the function menu_get_object();
Example:
$node = menu_get_object();
$contentType = node_type_get_name($node);
Drupal 8 has another method. Check this out:
arg() is deprecated

Resources