Projet

Général

Profil

Paste
Télécharger (15,1 ko) Statistiques
| Branche: | Révision:

root / drupal7 / sites / all / modules / media / modules / media_wysiwyg / includes / media_wysiwyg.filter.inc @ fc3d89c3

1
<?php
2

    
3
/**
4
 * @file
5
 * Functions related to the WYSIWYG editor and the media input filter.
6
 */
7

    
8
define('MEDIA_WYSIWYG_TOKEN_REGEX', '/\[\[.*?\]\]/s');
9

    
10
/**
11
 * Filter callback for media markup filter.
12
 *
13
 * @TODO check for security probably pass text through filter_xss
14
 */
15
function media_wysiwyg_filter($text, $filter, $format, $langcode, $cache, $cache_id) {
16
  $replacements = array();
17
  $patterns = array();
18
  $rendered_text = $text;
19
  $count = 1;
20
  preg_match_all(MEDIA_WYSIWYG_TOKEN_REGEX, $text, $matches);
21
  if (!empty($matches[0])) {
22
    foreach ($matches[0] as $match) {
23
      $replacement = media_wysiwyg_token_to_markup(array($match), FALSE, $langcode);
24
      $rendered_text = str_replace($match, $replacement, $rendered_text, $count);
25
    }
26
  }
27
  return $rendered_text;
28
}
29

    
30
/**
31
 * Parses the contents of a CSS declaration block.
32
 *
33
 * @param string $declarations
34
 *   One or more CSS declarations delimited by a semicolon. The same as a CSS
35
 *   declaration block (see http://www.w3.org/TR/CSS21/syndata.html#rule-sets),
36
 *   but without the opening and closing curly braces. Also the same as the
37
 *   value of an inline HTML style attribute.
38
 *
39
 * @return array
40
 *   A keyed array. The keys are CSS property names, and the values are CSS
41
 *   property values.
42
 */
43
function media_wysiwyg_parse_css_declarations($declarations) {
44
  $properties = array();
45
  foreach (array_map('trim', explode(";", $declarations)) as $declaration) {
46
    if ($declaration != '') {
47
      list($name, $value) = array_map('trim', explode(':', $declaration, 2));
48
      $properties[strtolower($name)] = $value;
49
    }
50
  }
51
  return $properties;
52
}
53

    
54
/**
55
 * Replace callback to convert a media file tag into HTML markup.
56
 *
57
 * @param string $match
58
 *   Takes a match of tag code
59
 * @param bool $wysiwyg
60
 *   Set to TRUE if called from within the WYSIWYG text area editor.
61
 *
62
 * @return string
63
 *   The HTML markup representation of the tag, or an empty string on failure.
64
 *
65
 * @see media_wysiwyg_get_file_without_label()
66
 * @see hook_media_wysiwyg_token_to_markup_alter()
67
 */
68
function media_wysiwyg_token_to_markup($match, $wysiwyg = FALSE, $langcode = NULL) {
69
  static $recursion_stop;
70
  $settings = array();
71
  $match = str_replace("[[", "", $match);
72
  $match = str_replace("]]", "", $match);
73
  $tag = $match[0];
74

    
75
  try {
76
    if (!is_string($tag)) {
77
      throw new Exception('Unable to find matching tag');
78
    }
79

    
80
    $tag_info = drupal_json_decode($tag);
81

    
82
    if (!isset($tag_info['fid'])) {
83
      throw new Exception('No file Id');
84
    }
85

    
86
    // Ensure the 'link_text' key is always defined.
87
    if (!isset($tag_info['link_text'])) {
88
      $tag_info['link_text'] = NULL;
89
    }
90

    
91
    // Ensure a valid view mode is being requested.
92
    if (!isset($tag_info['view_mode'])) {
93
      $tag_info['view_mode'] = variable_get('media_wysiwyg_wysiwyg_default_view_mode', 'full');
94
    }
95
    elseif ($tag_info['view_mode'] != 'default') {
96
      $file_entity_info = entity_get_info('file');
97
      if (!in_array($tag_info['view_mode'], array_keys($file_entity_info['view modes']))) {
98
        // Media 1.x defined some old view modes that have been superseded by
99
        // more semantically named ones in File Entity. The media_update_7203()
100
        // function updates field settings that reference the old view modes,
101
        // but it's impractical to update all text content, so adjust
102
        // accordingly here.
103
        static $view_mode_updates = array(
104
          'media_preview' => 'preview',
105
          'media_small' => 'teaser',
106
          'media_large' => 'full',
107
        );
108
        if (isset($view_mode_updates[$tag_info['view_mode']])) {
109
          $tag_info['view_mode'] = $view_mode_updates[$tag_info['view_mode']];
110
        }
111
        else {
112
          throw new Exception('Invalid view mode');
113
        }
114
      }
115
    }
116

    
117
    $file = file_load($tag_info['fid']);
118
    if (!$file) {
119
      throw new Exception('Could not load media object');
120
    }
121
    // Check if we've got a recursion. Happens because a file_load() may
122
    // triggers file_entity_is_page() which then again triggers a file load.
123
    if (isset($recursion_stop[$file->fid])) {
124
      return '';
125
    }
126
    $recursion_stop[$file->fid] = TRUE;
127

    
128
    $tag_info['file'] = $file;
129

    
130
    // The class attributes is a string, but drupal requires it to be
131
    // an array, so we fix it here.
132
    if (!empty($tag_info['attributes']['class'])) {
133
      $tag_info['attributes']['class'] = explode(" ", $tag_info['attributes']['class']);
134
    }
135

    
136
    // Grab the potentially overrided fields from the file.
137
    $fields = media_wysiwyg_filter_field_parser($tag_info);
138
    foreach ($fields as $key => $value) {
139
      $file->{$key} = $value;
140
    }
141

    
142
    $attributes = is_array($tag_info['attributes']) ? $tag_info['attributes'] : array();
143
    $attribute_whitelist = variable_get('media_wysiwyg_wysiwyg_allowed_attributes', _media_wysiwyg_wysiwyg_allowed_attributes_default());
144
    $settings['attributes'] = array_intersect_key($attributes, array_flip($attribute_whitelist));
145
    $settings['fields'] = $fields;
146

    
147
    if (!empty($tag_info['attributes']) && is_array($tag_info['attributes'])) {
148
      $settings['attributes'] = array_intersect_key($tag_info['attributes'], array_flip($attribute_whitelist));
149
      $settings['fields'] = $fields;
150

    
151
      // Many media formatters will want to apply width and height independently
152
      // of the style attribute or the corresponding HTML attributes, so pull
153
      // these two out into top-level settings. Different WYSIWYG editors have
154
      // different behavior with respect to whether they store user-specified
155
      // dimensions in the HTML attributes or the style attribute - check both.
156
      // Per http://www.w3.org/TR/html5/the-map-element.html#attr-dim-width, the
157
      // HTML attributes are merely hints: CSS takes precedence.
158
      if (isset($settings['attributes']['style'])) {
159
        $css_properties = media_wysiwyg_parse_css_declarations($settings['attributes']['style']);
160
        foreach (array('width', 'height') as $dimension) {
161
          if (isset($css_properties[$dimension]) && substr($css_properties[$dimension], -2) == 'px') {
162
            $settings[$dimension] = substr($css_properties[$dimension], 0, -2);
163
          }
164
          elseif (isset($settings['attributes'][$dimension])) {
165
            $settings[$dimension] = $settings['attributes'][$dimension];
166
          }
167
        }
168
      }
169
      foreach (array('title', 'alt') as $field_type) {
170
        if (isset($settings['attributes'][$field_type])) {
171
          $settings['attributes'][$field_type] = decode_entities($settings['attributes'][$field_type]);
172
        }
173
      }
174
    }
175
  }
176
  catch (Exception $e) {
177
    watchdog('media', 'Unable to render media from %tag. Error: %error', array('%tag' => $tag, '%error' => $e->getMessage()));
178
    return '';
179
  }
180

    
181
  // If the tag has link text stored with it, override the filename with it for
182
  // the rest of this function, so that if the file is themed as a link, the
183
  // desired text will be used (see, for example, theme_file_link()).
184
  // @todo: Try to find a less hacky way to do this.
185
  if (isset($tag_info['link_text'])) {
186
    // The link text will have characters such as "&" encoded for HTML, but the
187
    // filename itself needs the raw value when it is used to build the link,
188
    // in order to avoid double encoding.
189
    $file->filename = decode_entities($tag_info['link_text']);
190
  }
191

    
192
  if ($wysiwyg) {
193
    $settings['wysiwyg'] = $wysiwyg;
194
    // If sending markup to a WYSIWYG, we need to pass the file information so
195
    // that an inline macro can be generated when the WYSIWYG is detached.
196
    // The WYSIWYG plugin is expecting this information in the
197
    // Drupal.settings.mediaDataMap variable.
198
    $element = media_wysiwyg_get_file_without_label($file, $tag_info['view_mode'], $settings, $langcode);
199
    $data = array(
200
      'type' => 'media',
201
      'fid'  => $file->fid,
202
      'view_mode' => $tag_info['view_mode'],
203
      'link_text' => $tag_info['link_text'],
204
    );
205
    drupal_add_js(array('mediaDataMap' => array($file->fid => $data)), 'setting');
206
    $element['#attributes']['data-fid'] = $file->fid;
207
    $element['#attributes']['data-media-element'] = '1';
208
    $element['#attributes']['class'][] = 'media-element';
209
  }
210
  else {
211
    // Display the field elements.
212
    $element = array();
213
    // Render the file entity, for sites using the file_entity rendering method.
214
    if (variable_get('media_wysiwyg_default_render', 'file_entity') == 'file_entity') {
215
      $element['content'] = file_view($file, $tag_info['view_mode']);
216
    }
217
    $element['content']['file'] = media_wysiwyg_get_file_without_label($file, $tag_info['view_mode'], $settings, $langcode);
218
    // Overwrite or set the file #alt attribute if it has been set in this
219
    // instance.
220
    if (!empty($element['content']['file']['#attributes']['alt'])) {
221
      $element['content']['file']['#alt'] = $element['content']['file']['#attributes']['alt'];
222
    }
223
    // Overwrite or set the file #title attribute if it has been set in this
224
    // instance.
225
    if (!empty($element['content']['file']['#attributes']['title'])) {
226
      $element['content']['file']['#title'] = $element['content']['file']['#attributes']['title'];
227
    }
228
    // For sites using the legacy field_attach rendering method, attach fields.
229
    if (variable_get('media_wysiwyg_default_render', 'file_entity') == 'field_attach') {
230
      field_attach_prepare_view('file', array($file->fid => $file), $tag_info['view_mode'], $langcode);
231
      entity_prepare_view('file', array($file->fid => $file), $langcode);
232
      $element['content'] += field_attach_view('file', $file, $tag_info['view_mode'], $langcode);
233
    }
234
    if (count(element_children($element['content'])) > 1) {
235
      // Add surrounding divs to group them together.
236
      // We dont want divs when there are no additional fields to allow files
237
      // to display inline with text, without breaking p tags.
238
      $element['content']['#type'] = 'container';
239
      $element['content']['#attributes']['class'] = array(
240
        'media',
241
        'media-element-container',
242
        'media-' . $element['content']['file']['#view_mode']
243
      );
244
    }
245

    
246
    // Conditionally add a pre-render if the media filter output is be cached.
247
    $filters = filter_get_filters();
248
    if (!isset($filters['media_filter']['cache']) || $filters['media_filter']['cache']) {
249
      $element['#pre_render'][] = 'media_wysiwyg_pre_render_cached_filter';
250
    }
251
  }
252
  drupal_alter('media_wysiwyg_token_to_markup', $element, $tag_info, $settings, $langcode);
253
  $output = drupal_render($element);
254
  unset($recursion_stop[$file->fid]);
255
  return $output;
256
}
257

    
258
/**
259
 * Parse the field array from the collapsed AJAX string.
260
 */
261
function media_wysiwyg_filter_field_parser($tag_info) {
262
  $fields = array();
263
  if (isset($tag_info['fields'])) {
264
    foreach($tag_info['fields'] as $field_name => $field_value) {
265
      if (strpos($field_name, 'field_') === 0) {
266
        $parsed_field = explode('[', str_replace(']', '', $field_name));
267
        $ref = &$fields;
268

    
269
        // Each key of the field needs to be the child of the previous key.
270
        foreach ($parsed_field as $key) {
271
          if (!isset($ref[$key])) {
272
            $ref[$key] = array();
273
          }
274
          $ref = &$ref[$key];
275
        }
276

    
277
        // The value should be set at the deepest level.
278
        // Fields that use rich-text markup will be urlencoded.
279
        $ref = decode_entities($field_value);
280
      }
281
    }
282
  }
283
  return $fields;
284
}
285

    
286
/**
287
 * Creates map of inline media tags.
288
 *
289
 * Generates an array of [inline tags] => <html> to be used in filter
290
 * replacement and to add the mapping to JS.
291
 *
292
 * @param string $text
293
 *   The String containing text and html markup of textarea
294
 *
295
 * @return array
296
 *   An associative array with tag code as key and html markup as the value.
297
 *
298
 * @see media_process_form()
299
 * @see media_token_to_markup()
300
 */
301
function _media_wysiwyg_generate_tagMap($text) {
302
  // Making $tagmap static as this function is called many times and
303
  // adds duplicate markup for each tag code in Drupal.settings JS,
304
  // so in media_process_form it adds something like tagCode:<markup>,
305
  // <markup> and when we replace in attach see two duplicate images
306
  // for one tagCode. Making static would make function remember value
307
  // between function calls. Since media_process_form is multiple times
308
  // with same form, this function is also called multiple times.
309
  static $tagmap = array();
310
  preg_match_all("/\[\[.*?\]\]/s", $text, $matches, PREG_SET_ORDER);
311
  foreach ($matches as $match) {
312
    // We see if tagContent is already in $tagMap, if not we add it
313
    // to $tagmap.  If we return an empty array, we break embeddings of the same
314
    // media multiple times.
315
    if (empty($tagmap[$match[0]])) {
316
      // @TODO: Total HACK, but better than nothing.
317
      // We should find a better way of cleaning this up.
318
      if ($markup_for_media = media_wysiwyg_token_to_markup($match, TRUE)) {
319
        $tagmap[$match[0]] = $markup_for_media;
320
      }
321
      else {
322
        $missing = file_create_url(drupal_get_path('module', 'media') . '/images/icons/default/image-x-generic.png');
323
        $tagmap[$match[0]] = '<div><img src="' . $missing . '" width="100px" height="100px"/></div>';
324
      }
325
    }
326
  }
327
  return $tagmap;
328
}
329

    
330
/**
331
 * Return a list of view modes allowed for a file embedded in the WYSIWYG.
332
 *
333
 * @param object $file
334
 *   A file entity.
335
 *
336
 * @return array
337
 *   An array of view modes that can be used on the file when embedded in the
338
 *   WYSIWYG.
339
 *
340
 * @deprecated
341
 */
342
function media_wysiwyg_get_wysiwyg_allowed_view_modes($file) {
343
  $enabled_view_modes = &drupal_static(__FUNCTION__, array());
344

    
345
  // @todo Add more caching for this.
346
  if (!isset($enabled_view_modes[$file->type])) {
347
    $enabled_view_modes[$file->type] = array();
348

    
349
    // Add the default view mode by default.
350
    $enabled_view_modes[$file->type]['default'] = array('label' => t('Default'), 'custom settings' => TRUE);
351

    
352
    $entity_info = entity_get_info('file');
353
    $view_mode_settings = field_view_mode_settings('file', $file->type);
354
    foreach ($entity_info['view modes'] as $view_mode => $view_mode_info) {
355
      // Do not show view modes that don't have their own settings and will
356
      // only fall back to the default view mode.
357
      if (empty($view_mode_settings[$view_mode]['custom_settings'])) {
358
        continue;
359
      }
360

    
361
      // Don't present the user with an option to choose a view mode in which
362
      // the file is hidden.
363
      $extra_fields = field_extra_fields_get_display('file', $file->type, $view_mode);
364
      if (empty($extra_fields['file']['visible'])) {
365
        continue;
366
      }
367

    
368
      // Add the view mode to the list of enabled view modes.
369
      $enabled_view_modes[$file->type][$view_mode] = $view_mode_info;
370
    }
371
  }
372

    
373
  $view_modes = $enabled_view_modes[$file->type];
374
  drupal_alter('media_wysiwyg_allowed_view_modes', $view_modes, $file);
375
  // Invoke the deprecated/misspelled alter hook as well.
376
  drupal_alter('media_wysiwyg_wysiwyg_allowed_view_modes', $view_modes, $file);
377
  return $view_modes;
378
}
379

    
380
/**
381
 * #pre_render callback: Modify the element if the render cache is filtered.
382
 */
383
function media_wysiwyg_pre_render_cached_filter($element) {
384
  // Remove contextual links since they are not compatible with cached filtered
385
  // text.
386
  if (isset($element['content']['#contextual_links'])) {
387
    unset($element['content']['#contextual_links']);
388
  }
389

    
390
  return $element;
391
}