Projet

Général

Profil

Paste
Télécharger (27,5 ko) Statistiques
| Branche: | Révision:

root / drupal7 / sites / all / modules / media / modules / media_wysiwyg / media_wysiwyg.module @ e4215af7

1
<?php
2

    
3
/**
4
 * @file
5
 * Primarily Drupal hooks.
6
 */
7

    
8
// Functions for tracking the file usage of [[inline tags]].
9
require_once dirname(__FILE__) . '/includes/media_wysiwyg.file_usage.inc';
10

    
11
// Functions for working with [[inline tags]] and wysiwyg editors.
12
require_once dirname(__FILE__) . '/includes/media_wysiwyg.filter.inc';
13

    
14
// Functions for UUID support to embedded media.
15
require_once dirname(__FILE__) . '/includes/media_wysiwyg.uuid.inc';
16

    
17
// Functions for features integration.
18
require_once dirname(__FILE__) . '/includes/media_wysiwyg.features.inc';
19

    
20
/**
21
 * Implements hook_page_build().
22
 */
23
function media_wysiwyg_page_build(&$page) {
24
  // We need to load some minor CSS if media alignment is enabled.
25
  if (variable_get('media_wysiwyg_alignment', FALSE)) {
26
    $page['page_bottom']['media_wysiwyg']['#attached']['css'] = array(
27
      drupal_get_path('module', 'media_wysiwyg') . '/css/media_wysiwyg.base.css' => array(
28
        'every_page' => TRUE,
29
      ),
30
    );
31
  }
32
}
33

    
34
/**
35
 * Implements hook_hook_info().
36
 */
37
function media_wysiwyg_hook_info() {
38
  $hooks = array(
39
    'media_wysiwyg_allowed_attributes_alter',
40
    'media_wysiwyg_token_to_markup_alter',
41
    'media_wysiwyg_allowed_view_modes_alter',
42
    'media_wysiwyg_format_form_prepare_alter',
43
  );
44

    
45
  return array_fill_keys($hooks, array('group' => 'media_wysiwyg'));
46
}
47

    
48
/**
49
 * Implements hook_menu().
50
 */
51
function media_wysiwyg_menu() {
52
  $items = array();
53

    
54
  $items['media/%file/format-form'] = array(
55
    'title' => 'Style selector',
56
    'description' => 'Choose a format for a piece of media',
57
    'page callback' => 'drupal_get_form',
58
    'page arguments' => array('media_wysiwyg_format_form', 1),
59
    'access callback' => 'media_wysiwyg_access',
60
    'access arguments' => array('view', 1),
61
    'file' => 'includes/media_wysiwyg.pages.inc',
62
    'theme callback' => 'media_dialog_get_theme_name',
63
    'type' => MENU_CALLBACK,
64
  );
65

    
66
  return $items;
67
}
68

    
69
/**
70
 * Implements hook_permission().
71
 */
72
function media_wysiwyg_permission() {
73
  return array(
74
    'use media wysiwyg' => array(
75
      'title' => t('Use Media WYSIWYG in an editor'),
76
      // Marked restrict because the WYSIWYG forms generate image derivatives,
77
      // which could lead to a DoS security vulnerability.
78
      'restrict access' => TRUE,
79
    ),
80
  );
81
}
82

    
83
/**
84
 * Access callback for WYSIWYG Media.
85
 */
86
function media_wysiwyg_access($op, $file = NULL, $account = NULL) {
87
  return user_access('use media wysiwyg', $account) && file_entity_access($op, $file, $account);
88
}
89

    
90
/**
91
 * Implements hook_element_info_alter().
92
 */
93
function media_wysiwyg_element_info_alter(&$types) {
94
  $types['text_format']['#pre_render'][] = 'media_wysiwyg_pre_render_text_format';
95
}
96

    
97
/**
98
 * Builds a map of media tags in the element.
99
 *
100
 * Builds a map of the media tags in an element that are being rendered to their
101
 * rendered HTML. The map is stored in JS, so we can transform them when the
102
 * editor is being displayed.
103
 */
104
function media_wysiwyg_pre_render_text_format($element) {
105
  // filter_process_format() copies properties to the expanded 'value' child
106
  // element.
107
  if (!isset($element['format'])) {
108
    return $element;
109
  }
110

    
111
  $field = &$element['value'];
112
  $settings = array(
113
    'field' => $field['#id'],
114
  );
115

    
116
  if (!isset($field['#value']) && $field['#value'] != '') {
117
    return $element;
118
  }
119

    
120
  $tagmap = array();
121

    
122
  foreach (array('value', 'summary') as $column) {
123
    if (isset($element[$column]['#value'])) {
124
      $tagmap += _media_wysiwyg_generate_tagMap($element[$column]['#value']);
125
    }
126
  }
127

    
128
  if (!empty($tagmap)) {
129
    $element['#attached']['js'][] = array(
130
      'data' => array(
131
        'tagmap' => $tagmap,
132
      ),
133
      'type' => 'setting',
134
    );
135
  }
136

    
137
  // Load the media browser library.
138
  $element['#attached']['library'][] = array('media', 'media_browser');
139
  $element['#attached']['library'][] = array('media', 'media_browser_settings');
140

    
141
  // Add wysiwyg-specific settings.
142
  $settings = array(
143
    'wysiwyg_allowed_attributes' => media_wysiwyg_allowed_attributes(),
144
    'img_alt_field' => 'field_file_image_alt_text',
145
    'img_title_field' => 'field_file_image_title_text',
146
  );
147

    
148
  // The file_entity module lets you specify a string, possibly with tokens, for
149
  // the alt and title attributes of images. We need the actual field names instead.
150
  // If the variable only contains a token of the format [file:field_file_image_alt_text]
151
  // then it's possible to extract it.
152
  $alt_token = variable_get('file_entity_alt', '[file:field_file_image_alt_text]');
153
  $title_token = variable_get('file_entity_title', '[file:field_file_image_title_text]');
154
  $matches = array();
155
  if (preg_match('/^\[file:(field_[[:alnum:]_-]+)\]$/', trim($alt_token), $matches)) {
156
    $settings['img_alt_field'] = $matches[1];
157
  }
158
  if (preg_match('/^\[file:(field_[[:alnum:]_-]+)\]$/', trim($title_token), $matches)) {
159
    $settings['img_title_field'] = $matches[1];
160
  }
161

    
162
  $element['#attached']['js'][] = array(
163
    'data' => array(
164
      'media' => $settings,
165
      'mediaDoLinkText' => (boolean) variable_get('media_wysiwyg_use_link_text_for_filename', 1),
166
    ),
167
    'type' => 'setting',
168
  );
169

    
170
  // Add filter handling.
171
  $element['#attached']['js'][] = drupal_get_path('module', 'media_wysiwyg') . '/js/media_wysiwyg.filter.js';
172

    
173
  return $element;
174
}
175

    
176
/**
177
 * Implements hook_form_FORM_ID_alter().
178
 */
179
function media_wysiwyg_form_field_ui_field_edit_form_alter(&$form, &$form_state) {
180
  // Add a checkbox that marks this field as one that can be
181
  // overridden in the WYSIWYG.
182
  if ($form['#instance']['entity_type'] == 'file') {
183
    $field_type = $form['#field']['type'];
184
    $allowed_field_types = variable_get('media_wysiwyg_wysiwyg_override_field_types', array('text', 'text_long'));
185
    if (in_array($field_type, $allowed_field_types)) {
186
      $form['instance']['settings']['wysiwyg_override'] = array(
187
        '#type' => 'checkbox',
188
        '#title' => t('Override in WYSIWYG'),
189
        '#description' => t('If checked, then this field may be overridden in the WYSIWYG editor.'),
190
        '#default_value' => isset($form['#instance']['settings']['wysiwyg_override']) ? $form['#instance']['settings']['wysiwyg_override'] : FALSE,
191
      );
192
    }
193
  }
194
}
195

    
196
/**
197
 * Implements hook_form_FORM_ID_alter().
198
 */
199
function media_wysiwyg_form_wysiwyg_profile_form_alter(&$form, &$form_state) {
200
  // Add warnings if the media filter is disabled for the WYSIWYG's text format.
201
  $form['buttons']['drupal']['media']['#element_validate'][] = 'media_wysiwyg_wysiwyg_button_element_validate';
202
  $form['buttons']['drupal']['media']['#after_build'][] = 'media_wysiwyg_wysiwyg_button_element_validate';
203
  form_load_include($form_state, 'inc', 'media_wysiwyg', 'wysiwyg_plugins/media');
204
}
205

    
206
/**
207
 * Element validate callback for the media WYSIWYG button.
208
 */
209
function media_wysiwyg_wysiwyg_button_element_validate($element, &$form_state) {
210
  if (!empty($element['#value'])) {
211
    $format = filter_format_load($form_state['build_info']['args'][0]->format);
212
    $filters = filter_list_format($format->format);
213
    if (empty($filters['media_filter']->status)) {
214
      form_error($element, t('The <em>Convert Media tags to markup</em> filter must be enabled for the <a href="@format-link">@format format</a> in order to use the Media browser WYSIWYG button.', array(
215
        '@format-link' => url('admin/config/content/formats/' . $format->format, array('query' => array('destination' => $_GET['q']))),
216
        '@format' => $format->name,
217
      )));
218
    }
219
  }
220

    
221
  return $element;
222
}
223

    
224
/**
225
 * Implements hook_form_FORM_ID_alter().
226
 */
227
function media_wysiwyg_form_media_admin_config_browser_alter(&$form, &$form_state) {
228
  $form['wysiwyg'] = array(
229
    '#type' => 'fieldset',
230
    '#title' => t('WYSIWYG configuration'),
231
    '#collapsible' => TRUE,
232
    '#collapsed' => FALSE,
233
  );
234
  $form['wysiwyg']['media_wysiwyg_wysiwyg_browser_plugins'] = array(
235
    '#type' => 'checkboxes',
236
    '#title' => t('Enabled browser plugins'),
237
    '#options' => array(),
238
    '#required' => FALSE,
239
    '#default_value' => variable_get('media_wysiwyg_wysiwyg_browser_plugins', array()),
240
    '#description' => t('If no plugins are selected, they will all be available.'),
241
  );
242

    
243
  $plugins = media_get_browser_plugin_info();
244

    
245
  foreach ($plugins as $key => $plugin) {
246
    $form['wysiwyg']['media_wysiwyg_wysiwyg_browser_plugins']['#options'][$key] = !empty($plugin['title']) ? $plugin['title'] : $key;
247
  }
248

    
249
  $form['wysiwyg']['media_wysiwyg_wysiwyg_upload_directory'] = array(
250
    '#type' => 'textfield',
251
    '#title' => t("File directory for uploaded media"),
252
    '#default_value' => variable_get('media_wysiwyg_wysiwyg_upload_directory', ''),
253
    '#description' => t('Optional subdirectory within the upload destination where files will be stored. Do not include preceding or trailing slashes.'),
254
  );
255

    
256
  if (module_exists('token')) {
257
    $form['wysiwyg']['media_wysiwyg_wysiwyg_upload_directory']['#description'] .= t('This field supports tokens.');
258
    $form['wysiwyg']['tokens'] = array(
259
      '#theme' => 'token_tree',
260
      '#dialog' => TRUE,
261
    );
262
  }
263

    
264
  $form['wysiwyg']['media_wysiwyg_default_render'] = array(
265
    '#type' => 'radios',
266
    '#title' => t('How should file entities be rendered within a text field?'),
267
    '#description' => t("Full file entity rendering is the best choice for most sites. It respects the file entity's display settings specified at admin/structure/file-types. If your site already uses the legacy method, note that changing this option will affect your site's markup. Testing it on a non-production site is recommended."),
268
    '#options' => array(
269
      'file_entity' => 'Full file entity rendering',
270
      'field_attach' => 'Legacy rendering (using field attach)',
271
    ),
272
    '#default_value' => variable_get('media_wysiwyg_default_render', 'file_entity'),
273
  );
274

    
275
  $form['wysiwyg']['media_wysiwyg_wysiwyg_allowed_types'] = array(
276
    '#type' => 'checkboxes',
277
    '#title' => t('Allowed types in WYSIWYG'),
278
    '#options' => file_entity_type_get_names(),
279
    '#default_value' => variable_get('media_wysiwyg_wysiwyg_allowed_types', array('audio', 'image', 'video', 'document')),
280
  );
281

    
282
  $options = array();
283
  foreach(field_info_field_types() as $key => $type) {
284
    $options[$key] = (!empty($type['label']))? $type['label'] : ucfirst(str_replace("_"," ",$key));
285
  }
286
  asort($options);
287
  $form['wysiwyg']['media_wysiwyg_wysiwyg_override_field_types'] = array(
288
    '#type' => 'checkboxes',
289
    '#title' => t('Override field types in WYSIWYG'),
290
    '#options' => $options,
291
    '#default_value' => variable_get('media_wysiwyg_wysiwyg_override_field_types', array('text', 'text_long')),
292
    '#description' => t('If checked, then the field type may be overridden in the WYSIWYG editor. Not all field types/widgets (e.g. Term reference autocomplete) currently support being overridden so the desired result might not be achieved.')
293
  );
294

    
295
  $form['wysiwyg']['media_wysiwyg_wysiwyg_override_multivalue'] = array(
296
    '#type' => 'checkbox',
297
    '#title' => t('Override multi-value fields in WYSIWYG'),
298
    '#description' => t('If checked, then multi-value fields may be overridden in the WYSIWYG editor. Not all field types/widgets (e.g. Term reference autocomplete) currently support being overridden so the desired result might not be achieved.'),
299
    '#default_value' => variable_get('media_wysiwyg_wysiwyg_override_multivalue', FALSE),
300
  );
301

    
302
  $form['wysiwyg']['media_wysiwyg_use_link_text_for_filename'] = array(
303
    '#type' => 'checkbox',
304
    '#title' => t("Use link text for filename"),
305
    '#default_value' => variable_get('media_wysiwyg_use_link_text_for_filename', 1),
306
    '#description' => t('When formatting inserted media, allow editable link text to be used in place of the filename. Turn this off if your file view modes handle link formatting.'),
307
  );
308

    
309
  $form['wysiwyg']['media_wysiwyg_alignment'] = array(
310
    '#type' => 'checkbox',
311
    '#title' => t('Provide alignment option when embedding media'),
312
    '#default_value' => variable_get('media_wysiwyg_alignment', FALSE),
313
    '#description' => t('If checked, there will be an alignment (left/right/center) option when embedding media in a WYSIWYG.'),
314
  );
315

    
316
  $form['wysiwyg']['media_wysiwyg_external_link'] = array(
317
    '#type' => 'checkbox',
318
    '#title' => t('Provide the ability to link media to pages'),
319
    '#default_value' => variable_get('media_wysiwyg_external_link', FALSE),
320
    '#description' => t('If checked there will be a new field when embedding that will allow users to link to the media to urls'),
321
  );
322

    
323
  $form['wysiwyg']['media_wysiwyg_remove_media_class'] = array(
324
    '#type' => 'checkbox',
325
    '#title' => t('Remove the ".media" class from embedded media'),
326
    '#description' => t('If checked, the ".media" class will be removed from embedded media. Particularlly for sites using Bootstrap, the ".media" class can cause CSS to be unexpectedly applied to embedded media.'),
327
    '#default_value' => variable_get('media_wysiwyg_remove_media_class', FALSE),
328
  );
329

    
330
  $form['#submit'][] = 'media_wysiwyg_admin_config_browser_pre_submit';
331
}
332

    
333
/**
334
 * Manipulate values before form is submitted.
335
 */
336
function media_wysiwyg_admin_config_browser_pre_submit(&$form, &$form_state) {
337
  $wysiwyg_browser_plugins = array_unique(array_values($form_state['values']['media_wysiwyg_wysiwyg_browser_plugins']));
338
  if (empty($wysiwyg_browser_plugins[0])) {
339
    variable_del('media_wysiwyg_wysiwyg_browser_plugins');
340
    unset($form_state['values']['media_wysiwyg_wysiwyg_browser_plugins']);
341
  }
342
}
343

    
344
/**
345
 * Implements hook_filter_info().
346
 */
347
function media_wysiwyg_filter_info() {
348
  $filters['media_filter'] = array(
349
    'title' => t('Convert Media tags to markup'),
350
    'description' => t('This filter will convert [[{type:media... ]] tags into markup. This must be enabled for the Media WYSIWYG integration to work with this input format. It is recommended to run this before the "@convert_urls" filter.', array('@convert_urls' => 'Convert URLs into links')),
351
    'process callback' => 'media_wysiwyg_filter',
352
    'weight' => 2,
353
    // @TODO not implemented
354
    'tips callback' => 'media_filter_tips',
355
  );
356

    
357
  $filters['media_filter_paragraph_fix'] = array(
358
    'title' => t('Ensure that embedded Media tags are not contained in paragraphs'),
359
    'description' => t('This filter will fix any paragraph tags surrounding embedded Media tags. This helps to avoid the chopped up markup that can result from unexpectedly closed paragraph tags. This filter should be positioned above (before) the "Convert Media tags to markup" filter.'),
360
    'process callback' => 'media_wysiwyg_filter_paragraph_fix',
361
    'settings callback' => '_media_filter_paragraph_fix_settings',
362
    'default settings' => array(
363
      'replace' => 0,
364
    ),
365
    'weight' => 1,
366
  );
367

    
368
  return $filters;
369
}
370

    
371
/**
372
 * Implements hook_wysiwyg_include_directory().
373
 */
374
function media_wysiwyg_wysiwyg_include_directory($type) {
375
  switch ($type) {
376
    case 'plugins':
377
      return 'wysiwyg_plugins';
378

    
379
      break;
380
  }
381
}
382

    
383
/**
384
 * Returns the set of allowed attributes for use with WYSIWYG.
385
 *
386
 * @return array
387
 *   An array of whitelisted attributes.
388
 */
389
function media_wysiwyg_allowed_attributes() {
390
  // Support the legacy variable for this.
391
  $allowed_attributes = variable_get('media_wysiwyg_wysiwyg_allowed_attributes', array(
392
    'alt',
393
    'title',
394
    'height',
395
    'width',
396
    'hspace',
397
    'vspace',
398
    'border',
399
    'align',
400
    'style',
401
    'class',
402
    'id',
403
    'usemap',
404
    'data-picture-group',
405
    'data-picture-align',
406
    'data-picture-mapping',
407
    'data-delta',
408
  ));
409
  drupal_alter('media_wysiwyg_allowed_attributes', $allowed_attributes);
410
  return $allowed_attributes;
411
}
412

    
413
/**
414
 * Returns a drupal_render() array for just the file portion of a file entity.
415
 *
416
 * Optional custom settings can override how the file is displayed.
417
 */
418
function media_wysiwyg_get_file_without_label($file, $view_mode, $settings = array(), $langcode = NULL) {
419
  // Get the override alt & title from the fields override array. Grab the
420
  // "special" field names from the token replacement in file_entity, then see
421
  // if an override is provided and needed.
422
  $pattern = '/\[(\w+):(\w+)\]/';
423
  $alt = variable_get('file_entity_alt', '[file:field_file_image_alt_text]');
424
  $title = variable_get('file_entity_title', '[file:field_file_image_title_text]');
425
  $overrides = array(
426
    'alt' => $alt,
427
    'title' => $title,
428
  );
429
  foreach ($overrides as $field_type => $field_name) {
430
    preg_match($pattern, $field_name, $matches);
431
    if (!empty($matches[2])) {
432
      $field_name = $matches[2];
433
      $field_langcode = field_language('file', $file, $field_name);
434
      if (isset($settings['fields'][$field_name][$field_langcode]['value'])) {
435
        if (empty($settings['attributes'][$field_type])) {
436
          $settings['attributes'][$field_type] = $settings['fields'][$field_name][$field_langcode]['value'];
437
        }
438
      }
439
      if (isset($settings['fields'][$field_name][$field_langcode][0]['value'])) {
440
        if (empty($settings['attributes'][$field_type])) {
441
          $settings['attributes'][$field_type] = $settings['fields'][$field_name][$field_langcode][0]['value'];
442
        }
443
      }
444
    }
445
  }
446

    
447
  $file->override = $settings;
448

    
449
  $element = file_view_file($file, $view_mode, $langcode);
450

    
451
  // Field Translation Support.
452
  if (field_has_translation_handler('file')) {
453
    if ($field_items = field_get_items('file', $file, 'field_file_image_alt_text', $langcode)) {
454
      $value = field_view_value('file', $file, 'field_file_image_alt_text', $field_items[0], array(), $langcode);
455
      $element['#alt'] = isset($value['#markup']) ? $value['#markup'] : '';
456
    }
457
  }
458

    
459
  // The formatter invoked by file_view_file() can use $file->override to
460
  // customize the returned render array to match the requested settings. To
461
  // support simple formatters that don't do this, set the element attributes to
462
  // what was requested, but not if the formatter applied its own logic for
463
  // element attributes.
464
  if (isset($settings['attributes'])) {
465
    if (empty($element['#attributes'])) {
466
      $element['#attributes'] = $settings['attributes'];
467
    }
468

    
469
    // While this function may be called for any file type, images are a common
470
    // use-case, and image theme functions have their own structure for render
471
    // arrays.
472
    if (isset($element['#theme'])) {
473
      // theme_image() and theme_image_style() require the 'alt' attributes to
474
      // be passed separately from the 'attributes' array. (see
475
      // http://drupal.org/node/999338). Until that's fixed, implement this
476
      // special-case logic. Image formatters using other theme functions are
477
      // responsible for their own 'alt' attribute handling. See
478
      // theme_media_formatter_large_icon() for an example.
479
      if (in_array($element['#theme'], array('image', 'image_style'))) {
480
        if (empty($element['#alt']) && isset($settings['attributes']['alt'])) {
481
          $element['#alt'] = $settings['attributes']['alt'];
482
        }
483
      }
484
      // theme_image_formatter() and any potential replacements, such as
485
      // theme_colorbox_image_formatter(), also require attribute handling.
486
      elseif (strpos($element['#theme'], 'image_formatter') !== FALSE) {
487
        // theme_image_formatter() requires the attributes to be
488
        // set on the item rather than the element itself.
489
        if (empty($element['#item']['attributes'])) {
490
          $element['#item']['attributes'] = $settings['attributes'];
491
        }
492

    
493
        // theme_image_formatter() also requires alt, title, height, and
494
        // width attributes to be set on the item rather than within its
495
        // attributes array.
496
        foreach (array('alt', 'title', 'width', 'height') as $attr) {
497
          if (isset($settings['attributes'][$attr])) {
498
            $element['#item'][$attr] = $settings['attributes'][$attr];
499
          }
500
        }
501
      }
502
    }
503
  }
504

    
505
  return $element;
506
}
507

    
508
/**
509
 * Returns an array containing the names of all fields that perform text filtering.
510
 */
511
function media_wysiwyg_filter_fields_with_text_filtering($entity_type, $entity) {
512
  list($entity_id, $revision_id, $bundle) = entity_extract_ids($entity_type, $entity);
513
  $fields = field_info_instances($entity_type, $bundle);
514

    
515
  // Get all of the fields on this entity that allow text filtering.
516
  $fields_with_text_filtering = array();
517
  foreach ($fields as $field_name => $field) {
518
    if (!empty($field['settings']['text_processing'])) {
519
      $fields_with_text_filtering[] = $field_name;
520
    }
521
  }
522

    
523
  return $fields_with_text_filtering;
524
}
525

    
526
/**
527
 * Return a list of view modes allowed for a file type.
528
 *
529
 * @param string $file_type
530
 *   A file type machine name.
531
 *
532
 * @return array
533
 *   An array of view modes that can be used on the file type.
534
 */
535
function media_wysiwyg_get_file_type_view_mode_options($file_type) {
536
  $enabled_view_modes = &drupal_static(__FUNCTION__, array());
537

    
538
  // @todo Add more caching for this.
539
  if (!isset($enabled_view_modes[$file_type])) {
540
    $enabled_view_modes[$file_type] = array();
541

    
542
    // Add the default view mode by default.
543
    $enabled_view_modes[$file_type]['default'] = t('Default');
544

    
545
    $entity_info = entity_get_info('file');
546
    $view_mode_settings = field_view_mode_settings('file', $file_type);
547
    foreach ($entity_info['view modes'] as $view_mode => $view_mode_info) {
548
      // Do not show view modes that don't have their own settings and will
549
      // only fall back to the default view mode.
550
      if (empty($view_mode_settings[$view_mode]['custom_settings'])) {
551
        continue;
552
      }
553

    
554
      // Don't present the user with an option to choose a view mode in which
555
      // the file is hidden.
556
      $extra_fields = field_extra_fields_get_display('file', $file_type, $view_mode);
557
      if (empty($extra_fields['file']['visible'])) {
558
        continue;
559
      }
560

    
561
      // Add the view mode to the list of enabled view modes.
562
      $enabled_view_modes[$file_type][$view_mode] = $view_mode_info['label'];
563
    }
564
  }
565

    
566
  return $enabled_view_modes[$file_type];
567
}
568

    
569
/**
570
 * Return a list of view modes allowed for a file embedded in the WYSIWYG.
571
 *
572
 * @param object $file
573
 *   A file entity.
574
 *
575
 * @return array
576
 *   An array of view modes that can be used on the file when embedded in the
577
 *   WYSIWYG.
578
 */
579
function media_wysiwyg_get_file_view_mode_options($file) {
580
  $view_modes = media_wysiwyg_get_file_type_view_mode_options($file->type);
581
  drupal_alter('media_wysiwyg_allowed_view_modes', $view_modes, $file);
582
  // Invoke the deprecated/misspelled alter hook as well.
583
  drupal_alter('media_wysiwyg_wysiwyg_allowed_view_modes', $view_modes, $file);
584
  return $view_modes;
585
}
586

    
587
/**
588
 * Implements hook_file_displays_alter().
589
 */
590
function media_wysiwyg_file_displays_alter(&$displays, $file, $view_mode) {
591
  // Override the fields of the file when requested by the WYSIWYG.
592
  if (isset($file->override) && isset($file->override['fields'])) {
593
    $instance = field_info_instances('file', $file->type);
594
    foreach ($file->override['fields'] as $field_name => $value) {
595
      if (!isset($instance[$field_name]['settings']) || !isset($instance[$field_name]['settings']['wysiwyg_override']) || $instance[$field_name]['settings']['wysiwyg_override']) {
596
        $file->{$field_name} = $value;
597
      }
598
    }
599
  }
600
  // For integration/support of the picture module https://www.drupal.org/project/picture.
601
  // Disable Picture display in WYSIWYG mode. Normal <img> will be rendered
602
  // instead. CKEditor and Media WYSIWYG modules with render with common <img>
603
  // while frontend will render full <picture> output as usual.
604
  if (module_exists('picture')) {
605
    if (!empty($file->override['wysiwyg']) && !empty($displays['file_field_picture']['status'])) {
606
      $displays['file_field_picture']['status'] = 0;
607
    }
608
  }
609
}
610

    
611
/**
612
 * Implements hook_entity_info_alter().
613
 *
614
 * Add a file type named 'WYSIWYG'.
615
 */
616
function media_wysiwyg_entity_info_alter(&$entity_info) {
617
  $entity_info['file']['view modes']['wysiwyg'] = array(
618
    'label' => t('WYSIWYG'),
619
    'custom settings' => TRUE,
620
  );
621
}
622

    
623
/**
624
 * Implements hook_form_FORM_ID_alter().
625
 *
626
 * Add select when editing file types to set wysiwyg view mode.
627
 */
628
function media_wysiwyg_form_file_entity_file_type_form_alter(&$form, &$form_state) {
629
  // #2609244 Keep media from trying to alter the File add form just edit.
630
  if (empty($form_state['build_info']['args'][0])) {
631
    return;
632
  }
633

    
634
  $options = array();
635

    
636
  // Add an option allowing users not to use a view mode.
637
  $options['none'] = t('None');
638

    
639
  // Add the default view mode by default.
640
  $options['default'] = t('Default');
641

    
642
  $entity_info = entity_get_info('file');
643
  foreach ($entity_info['view modes'] as $view_mode => $view_mode_info) {
644
    $options[$view_mode] = check_plain($view_mode_info['label']);
645
  }
646

    
647
  $file_type = $form['#file_type']->type;
648
  $view_mode = db_query('SELECT view_mode FROM {media_view_mode_wysiwyg} WHERE type = :type', array(':type' => $file_type))->fetchField();
649
  $view_mode = empty($view_mode) ? 'none' : $view_mode;
650

    
651
  $form['file_wysiwyg_view_mode'] = array(
652
    '#type' => 'select',
653
    '#title' => t('WYSIWYG view mode'),
654
    '#options' => $options,
655
    '#default_value' => $view_mode,
656
    '#description' => t('View mode to be used when displaying files inside of the WYSIWYG editor.'),
657
  );
658

    
659
  // Move submit after our select box. There might be a better way to do this.
660
  $form['submit']['#weight'] = 1;
661

    
662
  array_unshift($form['#submit'], 'media_wysiwyg_form_file_entity_file_type_form_alter_submit');
663
}
664

    
665
/**
666
 * Custom submit handler.
667
 *
668
 * Save wysiwyg view mode.
669
 *
670
 * @see media_wysiwyg_form_file_entity_file_type_form_alter().
671
 */
672
function media_wysiwyg_form_file_entity_file_type_form_alter_submit(&$form, &$form_state) {
673
  $file_type = $form['#file_type']->type;
674
  $view_mode = $form_state['values']['file_wysiwyg_view_mode'];
675
  db_delete('media_view_mode_wysiwyg')->condition('type', $file_type)->execute();
676
  if ($view_mode != 'none') {
677
    $record = array('type' => $file_type, 'view_mode' => $view_mode);
678
    drupal_write_record('media_view_mode_wysiwyg', $record);
679
  }
680
}
681

    
682
/**
683
 * Implements hook_form_FORM_ID_alter().
684
 *
685
 * Add checkbox to restrict file type view mode availability in wysiwyg.
686
 */
687
function media_wysiwyg_form_file_entity_file_display_form_alter(&$form, &$form_state) {
688
  $file_type = $form['#file_type'];
689
  $view_mode = $form['#view_mode'];
690

    
691
  if ($view_mode != 'none') {
692
    $restricted = db_query(
693
      'SELECT 1 FROM {media_restrict_wysiwyg} WHERE type = :type and display = :display',
694
      array(':type' => $file_type, ':display' => $view_mode)
695
    )->fetchField();
696
    $form['restrict_wysiwyg'] = array(
697
      '#type' => 'checkbox',
698
      '#title' => t('Restrict in WYSIWYG'),
699
      '#description' => t('If checked, then this mode will not be allowed from the WYSIWYG.'),
700
      '#default_value' => !empty($restricted),
701
    );
702
    array_unshift($form['#submit'], 'media_wysiwyg_form_file_entity_file_display_form_alter_submit');
703
  }
704

    
705
  return $form;
706
}
707

    
708
/**
709
 * Custom submit handler.
710
 *
711
 * Save restricted wysiwyg file types.
712
 *
713
 * @see media_wysiwyg_form_file_entity_file_display_form_alter().
714
 */
715
function media_wysiwyg_form_file_entity_file_display_form_alter_submit(&$form, &$form_state) {
716
  $file_type = $form['#file_type'];
717
  $view_mode = $form['#view_mode'];
718
  db_delete('media_restrict_wysiwyg')->condition('type', $file_type)->condition('display', $view_mode)->execute();
719
  if (!empty($form_state['values']['restrict_wysiwyg'])) {
720
    $record = array('type' => $file_type, 'display' => $view_mode);
721
    drupal_write_record('media_restrict_wysiwyg', $record);
722
  }
723
}
724

    
725
/**
726
 * Implements hook_media_browser_params_alter().
727
 */
728
function media_wysiwyg_media_browser_params_alter(&$params) {
729
  // Set the media browser options as defined in the interface.
730
  if (!empty($params['id']) && $params['id'] === 'media_wysiwyg') {
731
    $params = array(
732
      'enabledPlugins' => variable_get('media_wysiwyg_wysiwyg_browser_plugins', array()),
733
      'file_directory' => variable_get('media_wysiwyg_wysiwyg_upload_directory', ''),
734
      'types' => variable_get('media_wysiwyg_wysiwyg_allowed_types', array('audio', 'image', 'video', 'document')),
735
      'id' => 'media_wysiwyg',
736
    ) + $params;
737
  }
738
}