Projet

Général

Profil

Paste
Télécharger (22,2 ko) Statistiques
| Branche: | Révision:

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

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
    if (!isset($tag_info['fid'])) {
150
      throw new Exception('No file Id');
151
    }
152

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

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

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

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

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

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

    
209
    if (array_key_exists('attributes', $tag_info) && is_array($tag_info['attributes'])) {
210
      $attributes = $tag_info['attributes'];
211
    }
212
    else {
213
      $attributes = array();
214
    }
215
    $attribute_whitelist = media_wysiwyg_allowed_attributes();
216
    $settings['attributes'] = array_intersect_key($attributes, array_flip($attribute_whitelist));
217
    $settings['fields'] = $fields;
218
    if (isset($tag_info['fields']['external_url'])) {
219
      $settings['fields']['external_url'] = $tag_info['fields']['external_url'];
220
    }
221
    if (!empty($tag_info['attributes']) && is_array($tag_info['attributes'])) {
222
      $settings['attributes'] = array_intersect_key($tag_info['attributes'], array_flip($attribute_whitelist));
223

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

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

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

    
288
  if ($wysiwyg) {
289
    $settings['wysiwyg'] = $wysiwyg;
290

    
291
    // Render file in WYSIWYG using appropriate view mode.
292
    $view_mode = db_query('SELECT view_mode FROM {media_view_mode_wysiwyg} WHERE type = :type', array(
293
      ':type' => $file->type,
294
    ))
295
      ->fetchField();
296
    if (empty($view_mode)) {
297
      $view_mode = $tag_info['view_mode'];
298
    }
299

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

    
345
      // Add any float information via an extra class
346
      if (!empty($settings['float'])) {
347
        $element['content']['file']['#attributes']['class'][] = drupal_html_class('media-float-' . $settings['float']);
348
      }
349
    }
350
    if (count(element_children($element['content'])) > 1) {
351
      // Add surrounding divs to group them together.
352
      // We don't want divs when there are no additional fields to allow files
353
      // to display inline with text, without breaking p tags.
354
      $element['content']['#type'] = 'container';
355
      $element['content']['#attributes']['class'] = array(
356
        'media',
357
        'media-element-container',
358
        'media-' . $element['content']['file']['#view_mode'],
359
      );
360
      // Add the float information to the outer element.
361
      if (!empty($settings['float'])) {
362
        $element['content']['#attributes']['class'][] = drupal_html_class('media-float-' . $settings['float']);
363
      }
364
      if (variable_get('media_wysiwyg_remove_media_class', FALSE)) {
365
        $classes = $element['content']['#attributes']['class'];
366
        $element['content']['#attributes']['class'] = array_diff($classes, array('media'));
367
      }
368
    }
369

    
370
    // Conditionally add a pre-render if the media filter output is be cached.
371
    $filters = filter_get_filters();
372
    if (!isset($filters['media_filter']['cache']) || $filters['media_filter']['cache']) {
373
      $element['#pre_render'][] = 'media_wysiwyg_pre_render_cached_filter';
374
    }
375
  }
376
  if (!empty($element['content']) && !empty($tag_info['fields']['alignment'])) {
377
    // Set a CSS class if an alignment has been specified and is correct.
378
    $alignment = $tag_info['fields']['alignment'];
379
    if (in_array($alignment, array('left', 'right', 'center'))) {
380
      $alignment_class = 'media-wysiwyg-align-' . $alignment;
381
      $element['content']['#attributes']['class'][] = $alignment_class;
382
    }
383
  }
384
  drupal_alter('media_wysiwyg_token_to_markup', $element, $tag_info, $settings, $langcode);
385
  $output = drupal_render($element);
386
  unset($recursion_stop[$file->fid]);
387
  return $output;
388
}
389

    
390
/**
391
 * Parse the field array from the collapsed AJAX string.
392
 */
393
function media_wysiwyg_filter_field_parser($tag_info) {
394
  $fields = array();
395
  if (isset($tag_info['fields'])) {
396
    // Field names that end in [format] are associated with long-text fields that may have HTML Entities.
397
    // Those values will need to be URLDecoded as well as HTMLDecoded.
398
    $url_encoded_fields = array();
399
    foreach($tag_info['fields'] as $field_name => $field_value) {
400
      if (preg_match('/\[format\]$/', $field_name) > 0){
401
        $url_encoded_fields[] = preg_replace('/\[format\]$/', '[value]', $field_name);
402
      }
403
    }
404

    
405
    foreach($tag_info['fields'] as $field_name => $field_value) {
406
      if (strpos($field_name, 'field_') === 0) {
407
        $parsed_field = explode('[', str_replace(']', '', $field_name));
408
        $ref = &$fields;
409

    
410
        // Certain types of fields, because of differences in markup, end up
411
        // here with incomplete arrays. Make a best effort to support as many
412
        // types of fields as possible.
413
        // Single-value select lists show up here with only 2 array items.
414
        if (count($parsed_field) == 2) {
415
          $info = field_info_field($parsed_field[0]);
416
          if ($info && !empty($info['columns'])) {
417
            // Assume single-value.
418
            $parsed_field[] = 0;
419
            // Next tack on the column for this field.
420
            $parsed_field[] = key($info['columns']);
421
          }
422
        }
423
        // Multi-value select lists show up here with 3 array items.
424
        elseif (count($parsed_field) == 3 && (empty($parsed_field[2]) || is_numeric($parsed_field[2]))) {
425
          $info = field_info_field($parsed_field[0]);
426
          // They just need the value column.
427
          $parsed_field[3] = key($info['columns']);
428
        }
429

    
430
        // Each key of the field needs to be the child of the previous key.
431
        foreach ($parsed_field as $key) {
432
          if (!isset($ref[$key])) {
433
            $ref[$key] = array();
434
          }
435
          $ref = &$ref[$key];
436
        }
437

    
438
        // The value should be set at the deepest level.
439
        if (in_array($field_name, $url_encoded_fields)){
440
          // Fields that use rich-text markup will be urlencoded.
441
          $ref = urldecode(decode_entities($field_value));
442
        }
443
        else {
444
          // Only entities need to be decoded.
445
          $ref = decode_entities($field_value);
446
        }
447
      }
448
    }
449
  }
450
  return $fields;
451
}
452

    
453
/**
454
 * Creates map of inline media tags.
455
 *
456
 * Generates an array of [inline tags] => <html> to be used in filter
457
 * replacement and to add the mapping to JS.
458
 *
459
 * @param string $text
460
 *   The String containing text and html markup of textarea
461
 *
462
 * @return array
463
 *   An associative array with tag code as key and html markup as the value.
464
 *
465
 * @see media_process_form()
466
 * @see media_token_to_markup()
467
 */
468
function _media_wysiwyg_generate_tagMap($text) {
469
  // Making $tagmap static as this function is called many times and
470
  // adds duplicate markup for each tag code in Drupal.settings JS,
471
  // so in media_process_form it adds something like tagCode:<markup>,
472
  // <markup> and when we replace in attach see two duplicate images
473
  // for one tagCode. Making static would make function remember value
474
  // between function calls. Since media_process_form is multiple times
475
  // with same form, this function is also called multiple times.
476
  static $tagmap = array();
477
  preg_match_all("/\[\[(?!nid:).*?\]\]/s", $text, $matches, PREG_SET_ORDER);
478
  foreach ($matches as $match) {
479
    // We see if tagContent is already in $tagMap, if not we add it
480
    // to $tagmap.  If we return an empty array, we break embeddings of the same
481
    // media multiple times.
482
    if (empty($tagmap[$match[0]])) {
483
      // @TODO: Total HACK, but better than nothing.
484
      // We should find a better way of cleaning this up.
485
      if ($markup_for_media = media_wysiwyg_token_to_markup($match, TRUE)) {
486
        $tagmap[$match[0]] = $markup_for_media;
487
      }
488
      else {
489
        $missing = file_create_url(drupal_get_path('module', 'media') . '/images/icons/default/image-x-generic.png');
490
        $tagmap[$match[0]] = '<div><img src="' . $missing . '" width="100px" height="100px"/></div>';
491
      }
492
    }
493
  }
494
  return $tagmap;
495
}
496

    
497
/**
498
 * Return a list of view modes allowed for a file embedded in the WYSIWYG.
499
 *
500
 * @param object $file
501
 *   A file entity.
502
 *
503
 * @return array
504
 *   An array of view modes that can be used on the file when embedded in the
505
 *   WYSIWYG.
506
 *
507
 * @deprecated
508
 */
509
function media_wysiwyg_get_wysiwyg_allowed_view_modes($file) {
510
  $enabled_view_modes = &drupal_static(__FUNCTION__, array());
511

    
512
  // @todo Add more caching for this.
513
  if (!isset($enabled_view_modes[$file->type])) {
514
    $enabled_view_modes[$file->type] = array();
515

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

    
519
    $entity_info = entity_get_info('file');
520
    $view_mode_settings = field_view_mode_settings('file', $file->type);
521
    foreach ($entity_info['view modes'] as $view_mode => $view_mode_info) {
522
      // Do not show view modes that don't have their own settings and will
523
      // only fall back to the default view mode.
524
      if (empty($view_mode_settings[$view_mode]['custom_settings'])) {
525
        continue;
526
      }
527

    
528
      // Don't present the user with an option to choose a view mode in which
529
      // the file is hidden.
530
      $extra_fields = field_extra_fields_get_display('file', $file->type, $view_mode);
531
      if (empty($extra_fields['file']['visible'])) {
532
        continue;
533
      }
534

    
535
      // Add the view mode to the list of enabled view modes.
536
      $enabled_view_modes[$file->type][$view_mode] = $view_mode_info;
537
    }
538
  }
539

    
540
  $view_modes = $enabled_view_modes[$file->type];
541
  media_wysiwyg_wysiwyg_allowed_view_modes_restrict($view_modes, $file);
542
  drupal_alter('media_wysiwyg_allowed_view_modes', $view_modes, $file);
543
  // Invoke the deprecated/misspelled alter hook as well.
544
  drupal_alter('media_wysiwyg_wysiwyg_allowed_view_modes', $view_modes, $file);
545
  return $view_modes;
546
}
547
/**
548
 * Do not show restricted view modes.
549
 */
550
function media_wysiwyg_wysiwyg_allowed_view_modes_restrict(&$view_modes, &$file) {
551
  $restricted_view_modes = db_query('SELECT display FROM {media_restrict_wysiwyg} WHERE type = :type', array(':type' => $file->type))->fetchCol();
552
  foreach ($restricted_view_modes as $restricted_view_mode) {
553
    if (array_key_exists($restricted_view_mode, $view_modes)) {
554
      unset($view_modes[$restricted_view_mode]);
555
    }
556
  }
557
}
558
/**
559
 * #pre_render callback: Modify the element if the render cache is filtered.
560
 */
561
function media_wysiwyg_pre_render_cached_filter($element) {
562
  // Remove contextual links since they are not compatible with cached filtered
563
  // text.
564
  if (isset($element['content']['#contextual_links'])) {
565
    unset($element['content']['#contextual_links']);
566
  }
567

    
568
  return $element;
569
}