Newer
Older
/**
* @file
* Media API
*
* The core Media API.
* See http://drupal.org/project/media for more details.
Alex Bronstein
committed
// Code relating to using media as a field.
require_once dirname(__FILE__) . '/includes/media.fields.inc';
Jacob Singh
committed
/**
* Implements hook_hook_info().
*/
function media_hook_info() {
$hooks = array(
'media_parse',
'media_browser_plugin_info',
'media_browser_plugin_info_alter',
'media_browser_plugins_alter',
'media_browser_params_alter',
Paris Liakos
committed
'query_media_browser_alter',
);
return array_fill_keys($hooks, array('group' => 'media'));
}
* Implements hook_help().
function media_help($path, $arg) {
switch ($path) {
case 'admin/help#media':
$output = '';
$output .= '<h3>' . t('About') . '</h3>';
$output .= '<p>' . t('The Media module is a File Browser to the Internet, media provides a framework for managing files and multimedia assets, regardless of whether they are hosted on your own site or a 3rd party site. It replaces the Drupal core upload field with a unified User Interface where editors and administrators can upload, manage, and reuse files and multimedia assets. Media module also provides rich integration with WYSIWYG module to let content creators access media assets in rich text editor. Javascript is required to use the Media module. For more information check <a href="@media_faq">Media Module page</a>', array('@media_faq' => 'http://drupal.org/project/media')) . '.</p>';
$output .= '<h3>' . t('Uses') . '</h3>';
$output .= '<dl>';
$output .= '<dt>' . t('Media Repository') . '</dt>';
$output .= '<dd>' . t('Media module allows you to maintain a <a href="@mediarepo">media asset repository</a> where in you can add, remove, reuse your media assets. You can add the media file using upload form or from a url and also do bulk operations on the media assets.', array('@mediarepo' => url('admin/content/media'))) . '</dd>';
$output .= '<dt>' . t('Attaching media assets to content types') . '</dt>';
$output .= '<dd>' . t('Media assets can be attached to content types as fields. To add a media field to a <a href="@content-type">content type</a>, go to the content type\'s <em>manage fields</em> page, and add a new field of type <em>Multimedia Asset</em>.', array('@content-type' => url('admin/structure/types'))) . '</dd>';
$output .= '<dt>' . t('Using media assets in WYSIWYG') . '</dt>';
$output .= '<dd>' . t('Media module provides rich integration with WYSIWYG editors, using Media Browser plugin you can select media asset from library to add to the rich text editor moreover you can add media asset from the media browser itself using either upload method or add from url method. To configure media with WYSIWYG you need two steps of configuration:');
$output .= '<ul><li>' . t('Enable WYSIWYG plugin on your desired <a href="@wysiwyg-profile">WYSIWYG profile</a>. Please note that you will need to have <a href="@wysiwyg">WYSIWYG</a> module enabled.', array('@wysiwyg-profile' => url('admin/config/content/wysiwyg'), '@wysiwyg' => 'http://drupal.org/project/wysiwyg')) . '</li>';
$output .= '<li>' . t('Enable the <em>Convert Media tags to markup</em> filter on the <a href="@input-format">Input format</a> you are using with the WYSIWYG profile.', array('@input-format' => url('admin/config/content/formats'))) . '</li></ul></dd>';
return $output;
}
}
Alex Bronstein
committed
/**
* Implements hook_entity_info_alter().
*/
function media_entity_info_alter(&$entity_info) {
Paris Liakos
committed
// For sites that updated from Media 1.x, continue to provide these deprecated
// view modes.
// @see http://drupal.org/node/1051090
Devin Carlson
committed
if (variable_get('media_show_deprecated_view_modes', FALSE)) {
Markus Broman
committed
$entity_info['file']['view modes']['media_link'] = array(
'label' => t('Link'),
'custom settings' => TRUE,
);
$entity_info['file']['view modes']['media_original'] = array(
'label' => t('Original'),
'custom settings' => TRUE,
Paris Liakos
committed
);
}
Paris Liakos
committed
if (module_exists('entity_translation')) {
$entity_info['file']['translation']['entity_translation']['class'] = 'MediaEntityTranslationHandler';
Sascha Grossenbacher
committed
$entity_info['file']['translation']['entity_translation']['path schemes']['media'] = array('edit path' => 'media/%file/edit/%ctools_js');
Paris Liakos
committed
}
Alex Bronstein
committed
}
* Implements hook_menu().
*/
function media_menu() {
Jacob Singh
committed
// For managing different types of media and the fields associated with them.
$items['admin/config/media/browser'] = array(
'title' => 'Media browser settings',
'description' => 'Configure the behavior and display of the media browser.',
'page callback' => 'drupal_get_form',
'page arguments' => array('media_admin_config_browser'),
Brandon Neil
committed
'access arguments' => array('administer media browser'),
Jacob Singh
committed
);
Jacob Singh
committed
$items['admin/content/file/thumbnails'] = array(
'title' => 'Thumbnails',
'description' => 'Manage files used on your site.',
'page callback' => 'drupal_get_form',
'page arguments' => array('file_entity_admin_file'),
'access arguments' => array('administer files'),
'type' => MENU_LOCAL_TASK,
Jacob Singh
committed
'file' => 'file_entity.admin.inc',
'file path' => drupal_get_path('module', 'file_entity'),
Devin Carlson
committed
$items['media/ajax'] = array(
'page callback' => 'media_ajax_upload',
'delivery callback' => 'ajax_deliver',
'access arguments' => array('access content'),
'theme callback' => 'ajax_base_page_theme',
'type' => MENU_CALLBACK,
);
$items['media/browser'] = array(
'title' => 'Media browser',
'description' => 'Media Browser for picking media and uploading new media',
'page callback' => 'media_browser',
'access arguments' => array('access media browser'),
'type' => MENU_CALLBACK,
'theme callback' => 'media_dialog_get_theme_name',
);
// A testbed to try out the media browser with different launch commands.
$items['media/browser/testbed'] = array(
'title' => 'Media Browser test',
'description' => 'Make it easier to test media browser',
'page callback' => 'drupal_get_form',
'page arguments' => array('media_browser_testbed'),
'access arguments' => array('administer files'),
'type' => MENU_CALLBACK,
'file' => 'includes/media.browser.inc',
unknown
committed
// We could re-use the file/%file/edit path for the modal callback, but
// it is just easier to use our own namespace here.
$items['media/%file/edit/%ctools_js'] = array(
'title' => 'Edit',
'page callback' => 'drupal_get_form',
'page arguments' => array('media_file_edit_modal', 1, 3),
'access callback' => 'file_entity_access',
'access arguments' => array('update', 1),
'theme callback' => 'ajax_base_page_theme',
'file' => 'includes/media.pages.inc',
'type' => MENU_CALLBACK,
);
return $items;
/**
* Implements hook_menu_local_tasks_alter().
*/
function media_menu_local_tasks_alter(&$data, $router_item, $root_path) {
Dave Reid
committed
// Add action link to 'file/add' on 'admin/content/file/thumbnails' page.
if ($root_path == 'admin/content/file/thumbnails') {
$item = menu_get_item('file/add');
Dave Reid
committed
if (!empty($item['access'])) {
$data['actions']['output'][] = array(
'#theme' => 'menu_local_action',
'#link' => $item,
Dave Reid
committed
'#weight' => $item['weight'],
);
}
}
}
/**
* Implements hook_admin_paths().
*/
function media_admin_paths() {
$paths['media/*/edit/*'] = TRUE;
$paths['media/*/format-form'] = TRUE;
Dave Reid
committed
// If the media browser theme is set to the admin theme, ensure it gets set
// as an admin path as well.
Devin Carlson
committed
$dialog_theme = variable_get('media_dialog_theme', '');
Dave Reid
committed
if (empty($dialog_theme) || $dialog_theme == variable_get('admin_theme')) {
$paths['media/browser'] = TRUE;
$paths['media/browser/*'] = TRUE;
}
return $paths;
}
Dave Reid
committed
* Implements hook_permission().
*/
function media_permission() {
return array(
Brandon Neil
committed
'administer media browser' => array(
'title' => t('Administer media browser'),
'description' => t('Access media browser settings.'),
),
'access media browser' => array(
'title' => t('Use the media browser'),
),
);
}
* Implements hook_theme().
*/
function media_theme() {
return array(
'render element' => 'element',
),
// media.field.inc.
'media_widget' => array(
'render element' => 'element',
),
'media_widget_multiple' => array(
'render element' => 'element',
'media_upload_help' => array(
'variables' => array('description' => NULL),
),
'render element' => 'element',
'media_formatter_large_icon' => array(
Dave Reid
committed
'variables' => array('file' => NULL, 'attributes' => array(), 'style_name' => 'media_thumbnail'),
'media_dialog_page' => array(
'render element' => 'page',
'template' => 'templates/media-dialog-page',
'file' => 'includes/media.theme.inc',
Devin Carlson
committed
),
Devin Carlson
committed
/**
* Menu callback; Shared Ajax callback for media attachment and deletions.
*
* This rebuilds the form element for a particular field item. As long as the
* form processing is properly encapsulated in the widget element the form
* should rebuild correctly using FAPI without the need for additional callbacks
* or processing.
*/
function media_ajax_upload() {
$form_parents = func_get_args();
$form_build_id = (string) array_pop($form_parents);
if (empty($_POST['form_build_id']) || $form_build_id != $_POST['form_build_id']) {
// Invalid request.
drupal_set_message(t('An unrecoverable error occurred. The uploaded file likely exceeded the maximum file size (@size) that this server supports.', array('@size' => format_size(file_upload_max_size()))), 'error');
$commands = array();
$commands[] = ajax_command_replace(NULL, theme('status_messages'));
return array('#type' => 'ajax', '#commands' => $commands);
}
list($form, $form_state, $form_id, $form_build_id, $commands) = ajax_get_form();
Devin Carlson
committed
if (!$form) {
// Invalid form_build_id.
drupal_set_message(t('An unrecoverable error occurred. Use of this form has expired. Try reloading the page and submitting again.'), 'error');
$commands = array();
$commands[] = ajax_command_replace(NULL, theme('status_messages'));
return array('#type' => 'ajax', '#commands' => $commands);
}
// Get the current element and count the number of files.
$current_element = $form;
foreach ($form_parents as $parent) {
Brandon Lee
committed
if (isset($current_element[$parent])) {
$current_element = $current_element[$parent];
}
else {
$current_element = NULL;
break;
}
Devin Carlson
committed
}
$current_file_count = isset($current_element['#file_upload_delta']) ? $current_element['#file_upload_delta'] : 0;
Devin Carlson
committed
// Process user input. $form and $form_state are modified in the process.
drupal_process_form($form['#form_id'], $form, $form_state);
// Retrieve the element to be rendered.
foreach ($form_parents as $parent) {
$form = $form[$parent];
}
// Add the special Ajax class if a new file was added.
if (isset($form['#file_upload_delta']) && $current_file_count < $form['#file_upload_delta']) {
Devin Carlson
committed
$form[$current_file_count]['#attributes']['class'][] = 'ajax-new-content';
}
// Otherwise just add the new content class on a placeholder.
else {
$form['#suffix'] .= '<span class="ajax-new-content"></span>';
}
$output = theme('status_messages') . drupal_render($form);
$js = drupal_add_js();
$settings = call_user_func_array('array_merge_recursive', $js['settings']['data']);
$commands[] = ajax_command_replace(NULL, $output, $settings);
return array('#type' => 'ajax', '#commands' => $commands);
}
* Implements hook_image_default_styles().
function media_image_default_styles() {
$styles = array();
$styles['media_thumbnail'] = array(
'label' => 'Media thumbnail (100x100)',
'effects' => array(
array(
'name' => 'image_scale_and_crop',
'data' => array('width' => 100, 'height' => 100),
'weight' => 0,
),
),
);
return $styles;
* Implements hook_page_alter().
* This is used to use our alternate template when ?render=media-popup is passed
* in the URL.
function media_page_alter(&$page) {
if (isset($_GET['render']) && $_GET['render'] == 'media-popup') {
$page['#theme'] = 'media_dialog_page';
// Disable administration modules from adding output to the popup.
// @see http://drupal.org/node/914786
module_invoke_all('suppress', TRUE);
foreach (element_children($page) as $key) {
if ($key != 'content') {
unset($page[$key]);
Aaron Winborn
committed
/**
* Implements hook_form_FIELD_UI_FIELD_EDIT_FORM_alter().
*
* @todo: Respect field settings in 7.x-2.x and handle them in the media widget
* UI.
Aaron Winborn
committed
*/
function media_form_field_ui_field_edit_form_alter(&$form, &$form_state) {
// On file fields that use the media widget we need remove specific fields.
Aaron Winborn
committed
if ($form['#field']['type'] == 'file' && $form['instance']['widget']['type']['#value'] == 'media_generic') {
Aaron Winborn
committed
$form['instance']['settings']['file_extensions']['#title'] = t('Allowed file extensions for uploaded files');
$form['instance']['settings']['file_extensions']['#maxlength'] = 255;
$form['instance']['settings']['file_extensions']['#description'] .= '<br />' . t('If empty, the file extensions list will be composed automatically using the allowed file types.');
$form['instance']['settings']['file_extensions']['#required'] = FALSE;
Aaron Winborn
committed
}
// On image fields using the media widget we remove the alt/title fields.
Aaron Winborn
committed
if ($form['#field']['type'] == 'image' && $form['instance']['widget']['type']['#value'] == 'media_generic') {
$form['instance']['settings']['alt_field']['#access'] = FALSE;
$form['instance']['settings']['title_field']['#access'] = FALSE;
Aaron Winborn
committed
$form['instance']['settings']['file_extensions']['#title'] = t('Allowed file extensions for uploaded files');
// Do not increase maxlength of file extensions for image fields, since
// presumably they will not need a long list of extensions.
Aaron Winborn
committed
}
Devin Carlson
committed
// Add a validation function to any field instance which uses the media widget
// to ensure that the upload destination scheme is one of the allowed schemes
// if any defined by settings.
git
committed
if (isset($form['instance']['widget']) && $form['instance']['widget']['type']['#value'] == 'media_generic' && isset($form['#field']['settings']['uri_scheme'])) {
Devin Carlson
committed
$form['#validate'][] = 'media_field_instance_validate';
}
Aaron Winborn
committed
}
Devin Carlson
committed
/**
* Validation handler; ensure that the upload destination scheme is one of the
* allowed schemes.
*/
function media_field_instance_validate($form, &$form_state) {
Devin Carlson
committed
$allowed_schemes = array_filter($form_state['values']['instance']['widget']['settings']['allowed_schemes']);
Devin Carlson
committed
$upload_destination = $form_state['values']['field']['settings']['uri_scheme'];
Devin Carlson
committed
if (!empty($allowed_schemes) && !in_array($upload_destination, $allowed_schemes)) {
Devin Carlson
committed
form_set_error('allowed_schemes', t('The upload destination must be one of the allowed schemes.'));
}
}
Dave Reid
committed
/**
* Implements hook_form_alter().
Dave Reid
committed
*/
function media_form_alter(&$form, &$form_state, $form_id) {
Dave Reid
committed
// If we're in the media browser, set the #media_browser key to true
// so that if an ajax request gets sent to a different path, the form
// still uses the media_browser_form_submit callback.
if (current_path() == 'media/browser') {
if ($form_id == 'views_exposed_form') {
$form['render'] = array('#type' => 'hidden', '#value' => 'media-popup');
$form['#action'] = '/media/browser';
} else {
$form_state['#media_browser'] = TRUE;
}
Dave Reid
committed
}
// If the #media_browser key isset and is true we are using the browser
// popup, so add the media_browser submit handler.
Dave Reid
committed
if (!empty($form_state['#media_browser'])) {
$form['#submit'][] = 'media_browser_form_submit';
}
}
/**
* Submit handler; direction form submissions in the media browser.
*/
function media_browser_form_submit($form, &$form_state) {
$url = NULL;
$parameters = array();
// Single upload.
if (!empty($form_state['file'])) {
$file = $form_state['file'];
$url = 'media/browser';
$parameters = array('query' => array('render' => 'media-popup', 'fid' => $file->fid));
}
Paris Liakos
committed
// If $url is set, we had some sort of upload, so redirect the form.
if (!empty($url)) {
$form_state['redirect'] = array($url, $parameters);
}
}
* Implements hook_library().
*/
function media_library() {
$path = drupal_get_path('module', 'media');
Dave Reid
committed
$info = system_get_info('module', 'media');
$common = array(
'website' => 'http://drupal.org/project/media',
Dave Reid
committed
'version' => !empty($info['version']) ? $info['version'] : '7.x-2.x',
// Contains libraries common to other media modules.
$libraries['media_base'] = array(
'title' => 'Media base',
'js' => array(
$path . '/js/media.core.js' => array('group' => JS_LIBRARY, 'weight' => -5),
$path . '/js/util/json2.js' => array('group' => JS_LIBRARY),
$path . '/js/util/ba-debug.min.js' => array('group' => JS_LIBRARY),
),
'css' => array(
$path . '/css/media.css',
// Includes resources needed to launch the media browser. Should be included
// on pages where the media browser needs to be launched from.
$libraries['media_browser'] = array(
'title' => 'Media Browser popup libraries',
'js' => array(
$path . '/js/media.popups.js' => array('group' => JS_DEFAULT),
),
'dependencies' => array(
array('system', 'ui.resizable'),
array('system', 'ui.draggable'),
array('system', 'ui.dialog'),
array('media', 'media_base'),
// Resources needed in the media browser itself.
$libraries['media_browser_page'] = array(
'title' => 'Media browser',
'js' => array(
$path . '/js/media.browser.js' => array('group' => JS_DEFAULT),
),
'dependencies' => array(
array('system', 'ui.tabs'),
array('system', 'ui.draggable'),
array('system', 'ui.dialog'),
array('media', 'media_base'),
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
// Settings for the dialog etc.
$settings = array(
'browserUrl' => url('media/browser', array(
'query' => array(
'render' => 'media-popup'
))
),
'styleSelectorUrl' => url('media/-media_id-/format-form', array(
'query' => array(
'render' => 'media-popup'
))
),
'dialogOptions' => array(
'dialogclass' => variable_get('media_dialogclass', 'media-wrapper'),
'modal' => (boolean)variable_get('media_modal', TRUE),
'draggable' => (boolean)variable_get('media_draggable', FALSE),
'resizable' => (boolean)variable_get('media_resizable', FALSE),
'minwidth' => (int)variable_get('media_minwidth', 500),
'width' => (int)variable_get('media_width', 670),
'height' => (int)variable_get('media_height', 280),
'position' => variable_get('media_position', 'center'),
'overlay' => array(
'backgroundcolor' => variable_get('media_backgroundcolor', '#000000'),
'opacity' => (float)variable_get('media_opacity', 0.4),
),
'zindex' => (int)variable_get('media_zindex', 10000),
),
);
$libraries['media_browser_settings'] = array(
'title' => 'Media browser settings',
'js' => array(
0 => array(
'data' => array(
'media' => $settings,
),
'type' => 'setting',
),
),
);
foreach ($libraries as &$library) {
$library += $common;
}
return $libraries;
* Theme callback used to identify when we are in a popup dialog.
* Generally the default theme will look terrible in the media browser. This
* will default to the administration theme, unless set otherwise.
function media_dialog_get_theme_name() {
Devin Carlson
committed
return variable_get('media_dialog_theme', variable_get('admin_theme'));
* This will parse a url or embedded code into a unique URI.
* The function will call all modules implementing hook_media_parse($url),
* which should return either a string containing a parsed URI or NULL.
* @NOTE The implementing modules may throw an error, which will not be caught
* here; it's up to the calling function to catch any thrown errors.
* @NOTE In emfield, we originally also accepted an array of regex patterns
* to match against. However, that module used a registration for providers,
* and simply stored the match in the database keyed to the provider object.
* However, other than the stream wrappers, there is currently no formal
* registration for media handling. Additionally, few, if any, stream wrappers
* will choose to store a straight match from the parsed URL directly into
* the URI. Thus, we leave both the matching and the final URI result to the
* implementing module in this implementation.
* An alternative might be to do the regex pattern matching here, and pass a
* successful match back to the implementing module. However, that would
* require either an overloaded function or a new hook, which seems like more
* overhead than it's worth at this point.
* @TODO Once hook_module_implements_alter() is in core (see the issue at
* http://drupal.org/node/692950) we may want to implement media_media_parse()
* to ensure we were passed a valid URL, rather than an unsupported or
* malformed embed code that wasn't caught earlier. It will needed to be
* weighted so it's called after all other streams have a go, as the fallback,
* and will need to throw an error.
* @param string $url
* The original URL or embed code to parse.
*
* @return string
* The unique URI for the file, based on its stream wrapper, or NULL.
* @see media_parse_to_file()
* @see media_add_from_url_validate()
function media_parse_to_uri($url) {
// Trim any whitespace before parsing.
$url = trim($url);
foreach (module_implements('media_parse') as $module) {
$success = module_invoke($module, 'media_parse', $url);
$context = array(
'url' => $url,
'module' => $module,
);
drupal_alter('media_parse', $success, $context);
if (isset($success)) {
return $success;
}
}
* Parse a URL or embed code and return a file object.
* If a remote stream doesn't claim the parsed URL in media_parse_to_uri(),
* then we'll copy the file locally.
* @NOTE The implementing modules may throw an error, which will not be caught
* here; it's up to the calling function to catch any thrown errors.
* @see media_parse_to_uri()
* @see media_add_from_url_submit()
function media_parse_to_file($url) {
try {
$uri = media_parse_to_uri($url);
}
catch (Exception $e) {
// Pass the error along.
throw $e;
return;
}
if (isset($uri)) {
// Attempt to load an existing file from the unique URI.
$select = db_select('file_managed', 'f')
->extend('PagerDefault')
->fields('f', array('fid'))
->condition('uri', $uri);
$fid = $select->execute()->fetchCol();
if (!empty($fid)) {
$file = file_load(array_pop($fid));
return $file;
}
}
if (isset($uri)) {
// The URL was successfully parsed to a URI, but does not yet have an
// associated file: save it!
$file = file_uri_to_object($uri);
file_save($file);
}
else {
// The URL wasn't parsed. We'll try to save a remote file.
// Copy to temporary first.
$source_uri = file_stream_wrapper_uri_normalize('temporary://' . basename($url));
if (!@copy(@$url, $source_uri)) {
throw new Exception('Unable to add file ' . $url);
return;
}
$source_file = file_uri_to_object($source_uri);
$scheme = variable_get('file_default_scheme', 'public') . '://';
$uri = file_stream_wrapper_uri_normalize($scheme . $source_file->filename);
// Now to its new home.
$file = file_move($source_file, $uri, FILE_EXISTS_RENAME);
}
return $file;
* Utility function to recursively run check_plain on an array.
* @todo There is probably something in core I am not aware of that does this.
*/
function media_recursive_check_plain(&$value, $key) {
$value = check_plain($value);
}
* Implements hook_element_info().
function media_element_info() {
$types['media'] = array(
'#input' => TRUE,
Jacob Singh
committed
'#process' => array('media_element_process'),
Devin Carlson
committed
'#value_callback' => 'media_file_value',
'#element_validate' => array('media_element_validate'),
Devin Carlson
committed
'#pre_render' => array('media_element_pre_render'),
'#theme' => 'media_widget',
Devin Carlson
committed
'#theme_wrappers' => array('form_element'),
Devin Carlson
committed
'#size' => 22,
'#extended' => FALSE,
Jacob Singh
committed
'#media_options' => array(
'global' => array(
// Example: array('image', 'audio');
'types' => array(),
// Example: array('http', 'ftp', 'flickr');
'schemes' => array(),
Jacob Singh
committed
),
),
Jacob Singh
committed
'#attached' => array(
'library' => array(
array('media', 'media_browser'),
),
Jacob Singh
committed
),
Devin Carlson
committed
$setting = array();
$setting['media']['global'] = $types['media']['#media_options'];
$types['media']['#attached']['js'][] = array(
'type' => 'setting',
'data' => $setting,
);
return $types;
Alex Bronstein
committed
/**
* Process callback for the media form element.
Alex Bronstein
committed
*/
Devin Carlson
committed
function media_element_process($element, &$form_state, $form) {
unknown
committed
ctools_include('modal');
ctools_include('ajax');
ctools_modal_add_js();
// Append the '-upload' to the #id so the field label's 'for' attribute
// corresponds with the textfield element.
$original_id = $element['#id'];
$element['#id'] .= '-upload';
Devin Carlson
committed
$fid = isset($element['#value']['fid']) ? $element['#value']['fid'] : 0;
// Set some default element properties.
Devin Carlson
committed
$element['#file'] = $fid ? file_load($fid) : FALSE;
$element['#tree'] = TRUE;
$ajax_settings = array(
'path' => 'media/ajax/' . implode('/', $element['#array_parents']) . '/' . $form['form_build_id']['#value'],
'wrapper' => $original_id . '-ajax-wrapper',
Devin Carlson
committed
'effect' => 'fade',
);
// Set up the buttons first since we need to check if they were clicked.
$element['attach_button'] = array(
'#name' => implode('_', $element['#parents']) . '_attach_button',
'#type' => 'submit',
'#value' => t('Attach'),
'#validate' => array(),
'#submit' => array('media_file_submit'),
'#limit_validation_errors' => array($element['#parents']),
'#ajax' => $ajax_settings,
'#attributes' => array('class' => array('attach')),
Devin Carlson
committed
'#weight' => -1,
);
Jacob Singh
committed
$element['preview'] = array(
Devin Carlson
committed
'content' => array(),
'#prefix' => '<div class="preview">',
'#suffix' => '</div>',
Devin Carlson
committed
'#ajax' => $ajax_settings,
'#weight' => -10,
);
Devin Carlson
committed
// Substitute the JS preview for a true file thumbnail once the file is
// attached.
Devin Carlson
committed
$element['preview']['content'] = media_get_thumbnail_preview($element['#file']);
}
Devin Carlson
committed
// The file ID field itself.
$element['upload'] = array(
'#name' => 'media[' . implode('_', $element['#parents']) . ']',
'#type' => 'textfield',
'#title' => t('Enter the ID of an existing file'),
'#title_display' => 'invisible',
'#field_prefix' => t('File ID'),
'#size' => $element['#size'],
'#theme_wrappers' => array(),
'#attributes' => array('class' => array('upload')),
'#weight' => -9,
);
Devin Carlson
committed
$element['browse_button'] = array(
'#type' => 'link',
'#href' => '',
Devin Carlson
committed
'#title' => t('Browse'),
Devin Carlson
committed
'#attributes' => array('class' => array('button', 'browse', 'element-hidden')),
'#options' => array('fragment' => FALSE, 'external' => TRUE),
Devin Carlson
committed
'#weight' => -8,
);
Devin Carlson
committed
// Force the progress indicator for the remove button to be either 'none' or
// 'throbber', even if the upload button is using something else.
$ajax_settings['progress']['type'] = 'throbber';
$ajax_settings['progress']['message'] = NULL;
$ajax_settings['effect'] = 'none';
unknown
committed
$element['edit'] = array(
'#type' => 'link',
'#href' => 'media/' . $fid . '/edit/nojs',
'#title' => t('Edit'),
'#attributes' => array(
'class' => array(
// Required for CTools modal to work.
'ctools-use-modal',
unknown
committed
'ctools-modal-media-file-edit', 'button', 'edit',
),
),
'#weight' => 20,
'#access' => $element['#file'] ? file_entity_access('update', $element['#file']) : FALSE,
);
// If we have parent entity form/source langcodes, pass them in query. They
// will be used in
/* @see media_file_edit_modal() */
if (!empty($element['#media_parent_entity_form_langcode'])) {
$element['edit']['#options']['query']['media_parent_entity_form_langcode'] = $element['#media_parent_entity_form_langcode'];
if (!empty($element['#media_parent_entity_source_langcode'])) {
$element['edit']['#options']['query']['media_parent_entity_source_langcode'] = $element['#media_parent_entity_source_langcode'];
}
}
Devin Carlson
committed
$element['remove_button'] = array(
'#name' => implode('_', $element['#parents']) . '_remove_button',
'#type' => 'submit',
'#value' => t('Remove'),
'#validate' => array(),
'#submit' => array('media_file_submit'),
'#limit_validation_errors' => array($element['#parents']),
'#ajax' => $ajax_settings,
'#attributes' => array('class' => array('remove')),
Devin Carlson
committed
'#weight' => 0,
Jacob Singh
committed
);
$element['fid'] = array(
'#type' => 'hidden',
'#value' => $fid,
Jacob Singh
committed
'#attributes' => array('class' => array('fid')),
);
// Media browser attach code.
$element['#attached']['js'][] = drupal_get_path('module', 'media') . '/js/media.js';
Jacob Singh
committed
Steven Jones
committed
// IDs of form elements are 'unstable' in Drupal because of drupal_html_id
// add a class for our Javascript instead.
$element_js_class = drupal_html_class('js-media-element-' . $element['#id']);
$element['upload']['#attributes']['class'][] = $element_js_class;
Joseph Olstad
committed
// Cache the media options and pass the cache ID as a JavaScript setting.
$cid = drupal_get_token(drupal_random_bytes(32));
cache_set('media_options:' . $cid, $element['#media_options']['global'], 'cache_form', REQUEST_TIME + 21600);
Devin Carlson
committed
$element['browse_button']['#attached']['js'] = array(
array(
'type' => 'setting',
Joseph Olstad
committed
'data' => array('media' => array('elements' => array('.' . $element_js_class => array('global' => array('options' => $cid))))),
Devin Carlson
committed
)
Jacob Singh
committed
);
$element['#attached']['library'][] = array('media', 'media_browser');
$element['#attached']['library'][] = array('media', 'media_browser_settings');
Jacob Singh
committed
Devin Carlson
committed
// Prefix and suffix used for Ajax replacement.
$element['#prefix'] = '<div id="' . $original_id . '-ajax-wrapper">';
Devin Carlson
committed
$element['#suffix'] = '</div>';
Jacob Singh
committed
return $element;
Devin Carlson
committed
}
unknown
committed
/**
* Implements hook_form_FORM_ID_alter().
*/
function media_form_file_entity_edit_alter(&$form, &$form_state) {
// Make adjustments to the file edit form when used in a CTools modal.
if (!empty($form_state['ajax'])) {
// Remove the preview and the delete button.
$form['preview']['#access'] = FALSE;
$form['actions']['delete']['#access'] = FALSE;
// Convert the cancel link to a button which triggers a modal close.
$form['actions']['cancel']['#attributes']['class'][] = 'button';
$form['actions']['cancel']['#attributes']['class'][] = 'button-no';
$form['actions']['cancel']['#attributes']['class'][] = 'ctools-close-modal';
}
}
Devin Carlson
committed
/**
* The #value_callback for a media type element.
*/
function media_file_value(&$element, $input = FALSE, $form_state = NULL) {
$fid = 0;
// Find the current value of this field from the form state.
$form_state_fid = $form_state['values'];
foreach ($element['#parents'] as $parent) {
$form_state_fid = isset($form_state_fid[$parent]) ? $form_state_fid[$parent] : 0;
}
if ($element['#extended'] && isset($form_state_fid['fid'])) {
$fid = $form_state_fid['fid'];
}
elseif (is_numeric($form_state_fid)) {
$fid = $form_state_fid;
}
Devin Carlson
committed
// Process any input and attach files.
Devin Carlson
committed
if ($input !== FALSE) {
$return = $input;
Devin Carlson
committed
// Attachments take priority over all other values.
if ($file = media_attach_file($element)) {
Devin Carlson
committed
$fid = $file->fid;
}
Devin Carlson
committed
else {
// Check for #filefield_value_callback values.
// Because FAPI does not allow multiple #value_callback values like it
// does for #element_validate and #process, this fills the missing
// functionality to allow File fields to be extended through FAPI.
if (isset($element['#file_value_callbacks'])) {
foreach ($element['#file_value_callbacks'] as $callback) {
$callback($element, $input, $form_state);
}
}
// Load file if the FID has changed to confirm it exists.
if (isset($input['fid']) && $file = file_load($input['fid'])) {
$fid = $file->fid;
}
}
Devin Carlson
committed
}
// If there is no input, set the default value.
else {
if ($element['#extended']) {
$default_fid = isset($element['#default_value']['fid']) ? $element['#default_value']['fid'] : 0;
$return = isset($element['#default_value']) ? $element['#default_value'] : array('fid' => 0);
}
else {
$default_fid = isset($element['#default_value']) ? $element['#default_value'] : 0;
$return = array('fid' => 0);
}
// Confirm that the file exists when used as a default value.
if ($default_fid && $file = file_load($default_fid)) {
$fid = $file->fid;
}
}
$return['fid'] = $fid;
return $return;
Jacob Singh
committed
}
* Validate media form elements.
*
* The file type is validated during the upload process, but this is necessary
* necessary in order to respect the #required property.
*/
function media_element_validate(&$element, &$form_state) {
Devin Carlson
committed
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
$clicked_button = end($form_state['triggering_element']['#parents']);
// Check required property based on the FID.
if ($element['#required'] && empty($element['fid']['#value']) && !in_array($clicked_button, array('attach_button', 'remove_button'))) {
form_error($element['browse_button'], t('!name field is required.', array('!name' => $element['#title'])));
}
// Consolidate the array value of this field to a single FID.
if (!$element['#extended']) {
form_set_value($element, $element['fid']['#value'], $form_state);
}
}
/**
* Form submission handler for attach / remove buttons of media elements.
*
* @see media_element_process()
*/
function media_file_submit($form, &$form_state) {
// Determine whether it was the attach or remove button that was clicked, and
// set $element to the managed_file element that contains that button.
$parents = $form_state['triggering_element']['#array_parents'];
$button_key = array_pop($parents);
$element = drupal_array_get_nested_value($form, $parents);
// No action is needed here for the attach button, because all media
// attachments on the form are processed by media_file_value() regardless of
// which button was clicked. Action is needed here for the remove button,
// because we only remove a file in response to its remove button being
// clicked.
if ($button_key == 'remove_button') {
// If it's a temporary file we can safely remove it immediately, otherwise
// it's up to the implementing module to clean up files that are in use.
if ($element['#file'] && $element['#file']->status == 0) {
file_delete($element['#file']);
Devin Carlson
committed
// Update both $form_state['values'] and $form_state['input'] to reflect
// that the file has been removed, so that the form is rebuilt correctly.
// $form_state['values'] must be updated in case additional submit handlers
// run, and for form building functions that run during the rebuild, such as
// when the media element is part of a field widget.
// $form_state['input'] must be updated so that media_file_value() has
// correct information during the rebuild.
$values_element = $element['#extended'] ? $element['fid'] : $element;
form_set_value($values_element, NULL, $form_state);
drupal_array_set_nested_value($form_state['input'], $values_element['#parents'], NULL);
Devin Carlson
committed
// Set the form to rebuild so that $form is correctly updated in response to
// processing the file removal. Since this function did not change $form_state
// if the upload button was clicked, a rebuild isn't necessary in that
// situation and setting $form_state['redirect'] to FALSE would suffice.
// However, we choose to always rebuild, to keep the form processing workflow
// consistent between the two buttons.