Skip to content

Instantly share code, notes, and snippets.

@Quilted
Last active December 12, 2015 01:38
Show Gist options
  • Save Quilted/4692635 to your computer and use it in GitHub Desktop.
Save Quilted/4692635 to your computer and use it in GitHub Desktop.
Drupal 7: Allowing anonymous users access to Media module's browser

Drupal 7: Allowing anonymous users access to Media module's browser

What's up with Media module defaults?

To give anonymous users media permissions, know that Media module's permissions don't work as you might expect:

  • Import media files from the local filesystem: this is not for the media widget. You don't need to turn this on.
  • Edit media: You need this to upload files via the media widget.
  • Add media from remote services: straightforward.

The Library tab is not protected by any permissions. It's always included with the media browser plugin (aka the media widget).

How can I get around this madness?

You can get around this by implementing:

  • hook_permission() to create some finer tuned media permissions.
  • hook_media_browser_plugins_alter() to implement fine tuned permissions.
<?php
/**
* Implements hook_permission().
*
* Adds custom permissions to make media permissioning more fine tuned.
*/
function exhale_tour_permission() {
return array(
'media widget upload files' => array(
'title' => t('Upload files'),
'description' => t('Use the Media widget browser to upload files.'),
),
'media widget view library' => array(
'title' => t('View uploaded files'),
'description' => t('Use the Media widget browser to view and choose from uploaded files.'),
),
);
}
/**
* Implements hook_media_browser_plugins_alter().
*
* Uses custom permissions to ensure anonymous users don't have more access
* than desired.
*/
function exhale_tour_media_browser_plugins_alter(&$plugin_output) {
// Remove media library access if the current user doesn't have the
// correct permission.
if (!user_access('media widget view library')) {
unset($plugin_output['library']);
}
// Add the upload file tabe if the current user has the correct permission.
if (user_access('media widget upload files')) {
// Built from media.media.inc lines 53-62.
// Parameters from media.browser.inc line 11.
module_load_include('inc', 'media', 'includes/media.pages');
$params = drupal_get_query_parameters();
$attached = array();
$upload_form_id = 'media_add_upload';
$upload_form = drupal_get_form($upload_form_id, $params);
$plugin = array(
'#title' => t('Upload'),
'form' => array($upload_form),
'#attached' => $attached,
'#weight' => -10,
);
$plugin_output['upload'] = $plugin;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment