Projet

Général

Profil

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

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

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', '/\[\[.+?"type":"media".+?\]\]/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 = NULL, $format = NULL, $langcode = NULL, $cache = NULL, $cache_id = NULL) {
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
 * Filter callback to configure media_filter_paragraph_fix filter.
32
 */
33
function _media_filter_paragraph_fix_settings($form, &$form_state, $filter, $format, $defaults) {
34
  $filter->settings += $defaults;
35
  $settings['replace'] = array(
36
    '#type' => 'checkbox',
37
    '#title' => t('Replace paragraph tags with DIV.media-p tags'),
38
    '#default_value' => $filter->settings['replace'],
39
    '#description' => t('Default behaviour is to strip out parent P tags of media elements rather than replacing these.'),
40
  );
41
  return $settings;
42
}
43

    
44
/**
45
 * Filter callback to remove paragraph tags surrounding embedded media.
46
 */
47
function media_wysiwyg_filter_paragraph_fix($text, $filter) {
48
  $html_dom = filter_dom_load($text);
49
  // Store Nodes to remove to avoid inferferring with the NodeList iteration.
50
  $dom_nodes_to_remove = array();
51
  foreach ($html_dom->getElementsByTagName('p') as $paragraph) {
52
    if (preg_match(MEDIA_WYSIWYG_TOKEN_REGEX, $paragraph->nodeValue)) {
53
      if (empty($filter->settings['replace'])) {
54
        $sibling = $paragraph->firstChild;
55
        do {
56
          $next = $sibling->nextSibling;
57
          $paragraph->parentNode->insertBefore($sibling, $paragraph);
58
        } while ($sibling = $next);
59
        $dom_nodes_to_remove[] = $paragraph;
60
      }
61
      else {
62
        // Clone the P node into a DIV node.
63
        $div = $html_dom->createElement('div');
64
        $sibling = $paragraph->firstChild;
65
        do {
66
          $next = $sibling->nextSibling;
67
          $div->appendChild($sibling);
68
        } while ($sibling = $next);
69

    
70
        $classes = array('media-p');
71
        if ($paragraph->hasAttributes()) {
72
          foreach ($paragraph->attributes as $attr) {
73
            $name = $attr->nodeName;
74
            $value = $attr->nodeValue;
75
            if (strtolower($name) == 'class') {
76
              $classes[] = $value;
77
            }
78
            else {
79
              // Supressing errors with ID attribute or duplicate properties.
80
              @$div->setAttribute($name, $value);
81
            }
82
          }
83
        }
84
        $div->setAttribute('class', implode(' ', $classes));
85

    
86
        $paragraph->parentNode->insertBefore($div, $paragraph);
87
        $dom_nodes_to_remove[] = $paragraph;
88
      }
89
    }
90
  }
91
  foreach ($dom_nodes_to_remove as $paragraph) {
92
    $paragraph->parentNode->removeChild($paragraph);
93
  }
94
  $text = filter_dom_serialize($html_dom);
95
  return $text;
96
}
97

    
98
/**
99
 * Parses the contents of a CSS declaration block.
100
 *
101
 * @param string $declarations
102
 *   One or more CSS declarations delimited by a semicolon. The same as a CSS
103
 *   declaration block (see http://www.w3.org/TR/CSS21/syndata.html#rule-sets),
104
 *   but without the opening and closing curly braces. Also the same as the
105
 *   value of an inline HTML style attribute.
106
 *
107
 * @return array
108
 *   A keyed array. The keys are CSS property names, and the values are CSS
109
 *   property values.
110
 */
111
function media_wysiwyg_parse_css_declarations($declarations) {
112
  $properties = array();
113
  foreach (array_map('trim', explode(";", $declarations)) as $declaration) {
114
    if ($declaration != '') {
115
      list($name, $value) = array_map('trim', explode(':', $declaration, 2));
116
      $properties[strtolower($name)] = $value;
117
    }
118
  }
119
  return $properties;
120
}
121

    
122
/**
123
 * Replace callback to convert a media file tag into HTML markup.
124
 *
125
 * @param string $match
126
 *   Takes a match of tag code
127
 * @param bool $wysiwyg
128
 *   Set to TRUE if called from within the WYSIWYG text area editor.
129
 *
130
 * @return string
131
 *   The HTML markup representation of the tag, or an empty string on failure.
132
 *
133
 * @see media_wysiwyg_get_file_without_label()
134
 * @see hook_media_wysiwyg_token_to_markup_alter()
135
 */
136
function media_wysiwyg_token_to_markup($match, $wysiwyg = FALSE, $langcode = NULL) {
137
  static $recursion_stop;
138
  $settings = array();
139
  $match = str_replace("[[", "", $match);
140
  $match = str_replace("]]", "", $match);
141
  $tag = $match[0];
142

    
143
  try {
144
    if (!is_string($tag)) {
145
      throw new Exception('Unable to find matching tag');
146
    }
147

    
148
    $tag_info = drupal_json_decode($tag);
149

    
150
    if (!isset($tag_info['fid'])) {
151
      throw new Exception('No file Id');
152
    }
153

    
154
    // Ensure the 'link_text' key is always defined.
155
    if (!isset($tag_info['link_text'])) {
156
      $tag_info['link_text'] = NULL;
157
    }
158

    
159
    // Ensure a valid view mode is being requested.
160
    if (!isset($tag_info['view_mode'])) {
161
      $tag_info['view_mode'] = variable_get('media_wysiwyg_wysiwyg_default_view_mode', 'full');
162
    }
163
    elseif ($tag_info['view_mode'] != 'default') {
164
      $file_entity_info = entity_get_info('file');
165
      if (!in_array($tag_info['view_mode'], array_keys($file_entity_info['view modes']))) {
166
        // Media 1.x defined some old view modes that have been superseded by
167
        // more semantically named ones in File Entity. The media_update_7203()
168
        // function updates field settings that reference the old view modes,
169
        // but it's impractical to update all text content, so adjust
170
        // accordingly here.
171
        static $view_mode_updates = array(
172
          'media_preview' => 'preview',
173
          'media_small' => 'teaser',
174
          'media_large' => 'full',
175
        );
176
        if (isset($view_mode_updates[$tag_info['view_mode']])) {
177
          $tag_info['view_mode'] = $view_mode_updates[$tag_info['view_mode']];
178
        }
179
        else {
180
          throw new Exception('Invalid view mode');
181
        }
182
      }
183
    }
184

    
185
    $file = file_load($tag_info['fid']);
186
    if (!$file) {
187
      throw new Exception('Could not load media object');
188
    }
189
    // Check if we've got a recursion. Happens because a file_load() may
190
    // triggers file_entity_is_page() which then again triggers a file load.
191
    if (isset($recursion_stop[$file->fid])) {
192
      return '';
193
    }
194
    $recursion_stop[$file->fid] = TRUE;
195

    
196
    $tag_info['file'] = $file;
197

    
198
    // The class attributes is a string, but drupal requires it to be
199
    // an array, so we fix it here.
200
    if (!empty($tag_info['attributes']['class'])) {
201
      $tag_info['attributes']['class'] = explode(" ", $tag_info['attributes']['class']);
202
    }
203

    
204
    // Grab the potentially overridden fields from the file.
205
    $fields = media_wysiwyg_filter_field_parser($tag_info);
206
    foreach ($fields as $key => $value) {
207
      $file->{$key} = $value;
208
    }
209

    
210
    if (array_key_exists('attributes', $tag_info) && is_array($tag_info['attributes'])) {
211
      $attributes = $tag_info['attributes'];
212
    }
213
    else {
214
      $attributes = array();
215
    }
216
    $attribute_whitelist = media_wysiwyg_allowed_attributes();
217
    $settings['attributes'] = array_intersect_key($attributes, array_flip($attribute_whitelist));
218
    $settings['fields'] = $fields;
219

    
220
    if (!empty($tag_info['attributes']) && is_array($tag_info['attributes'])) {
221
      $settings['attributes'] = array_intersect_key($tag_info['attributes'], array_flip($attribute_whitelist));
222

    
223
      // Many media formatters will want to apply width and height independently
224
      // of the style attribute or the corresponding HTML attributes, so pull
225
      // these two out into top-level settings. Different WYSIWYG editors have
226
      // different behavior with respect to whether they store user-specified
227
      // dimensions in the HTML attributes or the style attribute - check both.
228
      // Per http://www.w3.org/TR/html5/the-map-element.html#attr-dim-width, the
229
      // HTML attributes are merely hints: CSS takes precedence.
230
      if (isset($settings['attributes']['style'])) {
231
        $css_properties = media_wysiwyg_parse_css_declarations($settings['attributes']['style']);
232
        foreach (array('width', 'height') as $dimension) {
233
          if (isset($css_properties[$dimension]) && substr($css_properties[$dimension], -2) == 'px') {
234
            $settings[$dimension] = substr($css_properties[$dimension], 0, -2);
235
          }
236
          elseif (isset($settings['attributes'][$dimension])) {
237
            $settings[$dimension] = $settings['attributes'][$dimension];
238
          }
239
        }
240
      }
241
      foreach (array('title', 'alt') as $field_type) {
242
        if (isset($settings['attributes'][$field_type])) {
243
          $settings['attributes'][$field_type] = decode_entities($settings['attributes'][$field_type]);
244
        }
245
      }
246
    }
247
    // Update file metadata from the potentially overridden tag info.
248
    foreach (array('width', 'height') as $dimension) {
249
      if (isset($settings['attributes'][$dimension])) {
250
        $file->metadata[$dimension] = $settings['attributes'][$dimension];
251
      }
252
    }
253
  }
254
  catch (Exception $e) {
255
    watchdog('media', 'Unable to render media from %tag. Error: %error', array('%tag' => $tag, '%error' => $e->getMessage()));
256
    return '';
257
  }
258

    
259
  // Remove any alignment classes from $settings, because it will be added later
260
  // in this function to the media's wrapper, and we don't want to confuse CSS
261
  // by having it on both the wrapper and the element.
262
  if (isset($settings['attributes']['class'])) {
263
    $alignment_classes = array(
264
      'media-wysiwyg-align-left',
265
      'media-wysiwyg-align-right',
266
      'media-wysiwyg-align-center',
267
    );
268
    $settings['attributes']['class'] = array_diff($settings['attributes']['class'], $alignment_classes);
269
  }
270

    
271
  // If the tag has link text stored with it, override the filename with it for
272
  // the rest of this function, so that if the file is themed as a link, the
273
  // desired text will be used (see, for example, theme_file_link()).
274
  // @todo: Try to find a less hacky way to do this.
275
  if (isset($tag_info['link_text']) && variable_get('media_wysiwyg_use_link_text_for_filename', 1)) {
276
    // The link text will have characters such as "&" encoded for HTML, but the
277
    // filename itself needs the raw value when it is used to build the link,
278
    // in order to avoid double encoding.
279
    $file->filename = decode_entities($tag_info['link_text']);
280
  }
281

    
282
  if ($wysiwyg) {
283
    $settings['wysiwyg'] = $wysiwyg;
284

    
285
    // Render file in WYSIWYG using appropriate view mode.
286
    $view_mode = db_query('SELECT view_mode FROM {media_view_mode_wysiwyg} WHERE type = :type', array(
287
      ':type' => $file->type,
288
    ))
289
      ->fetchField();
290
    if (empty($view_mode)) {
291
      $view_mode = $tag_info['view_mode'];
292
    }
293

    
294
    // If sending markup to a WYSIWYG, we need to pass the file information so
295
    // that an inline macro can be generated when the WYSIWYG is detached.
296
    // The WYSIWYG plugin is expecting this information in the
297
    // Drupal.settings.mediaDataMap variable.
298
    $element = media_wysiwyg_get_file_without_label($file, $view_mode, $settings, $langcode);
299
    $data = array(
300
      'type' => 'media',
301
      'fid'  => $file->fid,
302
      'view_mode' => $tag_info['view_mode'],
303
      'link_text' => $tag_info['link_text'],
304
    );
305
    drupal_add_js(array('mediaDataMap' => array($file->fid => $data)), 'setting');
306
    $element['#attributes']['data-fid'] = $file->fid;
307
    $element['#attributes']['data-media-element'] = '1';
308
    $element['#attributes']['class'][] = 'media-element';
309
  }
310
  else {
311
    // Display the field elements.
312
    $element = array();
313
    // Render the file entity, for sites using the file_entity rendering method.
314
    if (variable_get('media_wysiwyg_default_render', 'file_entity') == 'file_entity') {
315
      $element['content'] = file_view($file, $tag_info['view_mode']);
316
    }
317
    $element['content']['file'] = media_wysiwyg_get_file_without_label($file, $tag_info['view_mode'], $settings, $langcode);
318
    // Overwrite or set the file #alt attribute if it has been set in this
319
    // instance.
320
    if (!empty($element['content']['file']['#attributes']['alt'])) {
321
      $element['content']['file']['#alt'] = $element['content']['file']['#attributes']['alt'];
322
    }
323
    // Overwrite or set the file #title attribute if it has been set in this
324
    // instance.
325
    if (!empty($element['content']['file']['#attributes']['title'])) {
326
      $element['content']['file']['#title'] = $element['content']['file']['#attributes']['title'];
327
    }
328
    // For sites using the legacy field_attach rendering method, attach fields.
329
    if (variable_get('media_wysiwyg_default_render', 'file_entity') == 'field_attach') {
330
      field_attach_prepare_view('file', array($file->fid => $file), $tag_info['view_mode'], $langcode);
331
      entity_prepare_view('file', array($file->fid => $file), $langcode);
332
      $element['content'] += field_attach_view('file', $file, $tag_info['view_mode'], $langcode);
333
    }
334
    if (count(element_children($element['content'])) > 1) {
335
      // Add surrounding divs to group them together.
336
      // We don't want divs when there are no additional fields to allow files
337
      // to display inline with text, without breaking p tags.
338
      $element['content']['#type'] = 'container';
339
      $element['content']['#attributes']['class'] = array(
340
        'media',
341
        'media-element-container',
342
        'media-' . $element['content']['file']['#view_mode'],
343
      );
344
    }
345

    
346
    // Conditionally add a pre-render if the media filter output is be cached.
347
    $filters = filter_get_filters();
348
    if (!isset($filters['media_filter']['cache']) || $filters['media_filter']['cache']) {
349
      $element['#pre_render'][] = 'media_wysiwyg_pre_render_cached_filter';
350
    }
351
  }
352
  if (!empty($element['content']) && !empty($tag_info['fields']['alignment'])) {
353
    // Set a CSS class if an alignment has been specified and is correct.
354
    $alignment = $tag_info['fields']['alignment'];
355
    if (in_array($alignment, array('left', 'right', 'center'))) {
356
      $alignment_class = 'media-wysiwyg-align-' . $alignment;
357
      $element['content']['#attributes']['class'][] = $alignment_class;
358
    }
359
  }
360
  drupal_alter('media_wysiwyg_token_to_markup', $element, $tag_info, $settings, $langcode);
361
  $output = drupal_render($element);
362
  unset($recursion_stop[$file->fid]);
363
  return $output;
364
}
365

    
366
/**
367
 * Parse the field array from the collapsed AJAX string.
368
 */
369
function media_wysiwyg_filter_field_parser($tag_info) {
370
  $fields = array();
371
  if (isset($tag_info['fields'])) {
372
    // Field names that end in [format] are associated with long-text fields that may have HTML Entities.
373
    // Those values will need to be URLDecoded as well as HTMLDecoded.
374
    $url_encoded_fields = array();
375
    foreach($tag_info['fields'] as $field_name => $field_value) {
376
      if (preg_match('/\[format\]$/', $field_name) > 0){
377
        $url_encoded_fields[] = preg_replace('/\[format\]$/', '[value]', $field_name);
378
      }
379
    }
380

    
381
    foreach($tag_info['fields'] as $field_name => $field_value) {
382
      if (strpos($field_name, 'field_') === 0) {
383
        $parsed_field = explode('[', str_replace(']', '', $field_name));
384
        $ref = &$fields;
385

    
386
        // Certain types of fields, because of differences in markup, end up
387
        // here with incomplete arrays. Make a best effort to support as many
388
        // types of fields as possible.
389
        // Single-value select lists show up here with only 2 array items.
390
        if (count($parsed_field) == 2) {
391
          $info = field_info_field($parsed_field[0]);
392
          if ($info && !empty($info['columns'])) {
393
            // Assume single-value.
394
            $parsed_field[] = 0;
395
            // Next tack on the column for this field.
396
            $parsed_field[] = key($info['columns']);
397
          }
398
        }
399
        // Multi-value select lists show up here with 3 array items.
400
        elseif (count($parsed_field) == 3 && (empty($parsed_field[2]) || is_numeric($parsed_field[2]))) {
401
          $info = field_info_field($parsed_field[0]);
402
          // They just need the value column.
403
          $parsed_field[3] = key($info['columns']);
404
        }
405

    
406
        // Each key of the field needs to be the child of the previous key.
407
        foreach ($parsed_field as $key) {
408
          if (!isset($ref[$key])) {
409
            $ref[$key] = array();
410
          }
411
          $ref = &$ref[$key];
412
        }
413

    
414
        // The value should be set at the deepest level.
415
        if (in_array($field_name, $url_encoded_fields)){
416
          // Fields that use rich-text markup will be urlencoded.
417
          $ref = urldecode(decode_entities($field_value));
418
        }
419
        else {
420
          // Only entities need to be decoded.
421
          $ref = decode_entities($field_value);
422
        }
423
      }
424
    }
425
  }
426
  return $fields;
427
}
428

    
429
/**
430
 * Creates map of inline media tags.
431
 *
432
 * Generates an array of [inline tags] => <html> to be used in filter
433
 * replacement and to add the mapping to JS.
434
 *
435
 * @param string $text
436
 *   The String containing text and html markup of textarea
437
 *
438
 * @return array
439
 *   An associative array with tag code as key and html markup as the value.
440
 *
441
 * @see media_process_form()
442
 * @see media_token_to_markup()
443
 */
444
function _media_wysiwyg_generate_tagMap($text) {
445
  // Making $tagmap static as this function is called many times and
446
  // adds duplicate markup for each tag code in Drupal.settings JS,
447
  // so in media_process_form it adds something like tagCode:<markup>,
448
  // <markup> and when we replace in attach see two duplicate images
449
  // for one tagCode. Making static would make function remember value
450
  // between function calls. Since media_process_form is multiple times
451
  // with same form, this function is also called multiple times.
452
  static $tagmap = array();
453
  preg_match_all("/\[\[.*?\]\]/s", $text, $matches, PREG_SET_ORDER);
454
  foreach ($matches as $match) {
455
    // We see if tagContent is already in $tagMap, if not we add it
456
    // to $tagmap.  If we return an empty array, we break embeddings of the same
457
    // media multiple times.
458
    if (empty($tagmap[$match[0]])) {
459
      // @TODO: Total HACK, but better than nothing.
460
      // We should find a better way of cleaning this up.
461
      if ($markup_for_media = media_wysiwyg_token_to_markup($match, TRUE)) {
462
        $tagmap[$match[0]] = $markup_for_media;
463
      }
464
      else {
465
        $missing = file_create_url(drupal_get_path('module', 'media') . '/images/icons/default/image-x-generic.png');
466
        $tagmap[$match[0]] = '<div><img src="' . $missing . '" width="100px" height="100px"/></div>';
467
      }
468
    }
469
  }
470
  return $tagmap;
471
}
472

    
473
/**
474
 * Return a list of view modes allowed for a file embedded in the WYSIWYG.
475
 *
476
 * @param object $file
477
 *   A file entity.
478
 *
479
 * @return array
480
 *   An array of view modes that can be used on the file when embedded in the
481
 *   WYSIWYG.
482
 *
483
 * @deprecated
484
 */
485
function media_wysiwyg_get_wysiwyg_allowed_view_modes($file) {
486
  $enabled_view_modes = &drupal_static(__FUNCTION__, array());
487

    
488
  // @todo Add more caching for this.
489
  if (!isset($enabled_view_modes[$file->type])) {
490
    $enabled_view_modes[$file->type] = array();
491

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

    
495
    $entity_info = entity_get_info('file');
496
    $view_mode_settings = field_view_mode_settings('file', $file->type);
497
    foreach ($entity_info['view modes'] as $view_mode => $view_mode_info) {
498
      // Do not show view modes that don't have their own settings and will
499
      // only fall back to the default view mode.
500
      if (empty($view_mode_settings[$view_mode]['custom_settings'])) {
501
        continue;
502
      }
503

    
504
      // Don't present the user with an option to choose a view mode in which
505
      // the file is hidden.
506
      $extra_fields = field_extra_fields_get_display('file', $file->type, $view_mode);
507
      if (empty($extra_fields['file']['visible'])) {
508
        continue;
509
      }
510

    
511
      // Add the view mode to the list of enabled view modes.
512
      $enabled_view_modes[$file->type][$view_mode] = $view_mode_info;
513
    }
514
  }
515

    
516
  $view_modes = $enabled_view_modes[$file->type];
517
  media_wysiwyg_wysiwyg_allowed_view_modes_restrict($view_modes, $file);
518
  drupal_alter('media_wysiwyg_allowed_view_modes', $view_modes, $file);
519
  // Invoke the deprecated/misspelled alter hook as well.
520
  drupal_alter('media_wysiwyg_wysiwyg_allowed_view_modes', $view_modes, $file);
521
  return $view_modes;
522
}
523
/**
524
 * Do not show restricted view modes.
525
 */
526
function media_wysiwyg_wysiwyg_allowed_view_modes_restrict(&$view_modes, &$file) {
527
  $restricted_view_modes = db_query('SELECT display FROM {media_restrict_wysiwyg} WHERE type = :type', array(':type' => $file->type))->fetchCol();
528
  foreach ($restricted_view_modes as $restricted_view_mode) {
529
    if (array_key_exists($restricted_view_mode, $view_modes)) {
530
      unset($view_modes[$restricted_view_mode]);
531
    }
532
  }
533
}
534
/**
535
 * #pre_render callback: Modify the element if the render cache is filtered.
536
 */
537
function media_wysiwyg_pre_render_cached_filter($element) {
538
  // Remove contextual links since they are not compatible with cached filtered
539
  // text.
540
  if (isset($element['content']['#contextual_links'])) {
541
    unset($element['content']['#contextual_links']);
542
  }
543

    
544
  return $element;
545
}