Projet

Général

Profil

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

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

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
      }
242
      foreach (array('title', 'alt') as $field_type) {
243
        if (isset($settings['attributes'][$field_type])) {
244
          $settings['attributes'][$field_type] = decode_entities($settings['attributes'][$field_type]);
245
        }
246
      }
247
    }
248
    // Update file metadata from the potentially overridden tag info.
249
    foreach (array('width', 'height') as $dimension) {
250
      if (isset($settings['attributes'][$dimension])) {
251
        $file->metadata[$dimension] = $settings['attributes'][$dimension];
252
      }
253
    }
254
  }
255
  catch (Exception $e) {
256
    watchdog('media', 'Unable to render media from %tag. Error: %error', array('%tag' => $tag, '%error' => $e->getMessage()));
257
    return '';
258
  }
259

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
545
  return $element;
546
}