Projet

Général

Profil

Paste
Télécharger (20,4 ko) Statistiques
| Branche: | Révision:

root / drupal7 / modules / field / modules / text / text.module @ db2d93dd

1
<?php
2

    
3
/**
4
 * @file
5
 * Defines simple text field types.
6
 */
7

    
8
/**
9
 * Implements hook_help().
10
 */
11
function text_help($path, $arg) {
12
  switch ($path) {
13
    case 'admin/help#text':
14
      $output = '';
15
      $output .= '<h3>' . t('About') . '</h3>';
16
      $output .= '<p>' . t("The Text module defines various text field types for the Field module. A text field may contain plain text only, or optionally, may use Drupal's <a href='@filter-help'>text filters</a> to securely manage HTML output. Text input fields may be either a single line (text field), multiple lines (text area), or for greater input control, a select box, checkbox, or radio buttons. If desired, the field can be validated, so that it is limited to a set of allowed values. See the <a href='@field-help'>Field module help page</a> for more information about fields.", array('@field-help' => url('admin/help/field'), '@filter-help' => url('admin/help/filter'))) . '</p>';
17
      return $output;
18
  }
19
}
20

    
21
/**
22
 * Implements hook_field_info().
23
 *
24
 * Field settings:
25
 *   - max_length: the maximum length for a varchar field.
26
 * Instance settings:
27
 *   - text_processing: whether text input filters should be used.
28
 *   - display_summary: whether the summary field should be displayed.
29
 *     When empty and not displayed the summary will take its value from the
30
 *     trimmed value of the main text field.
31
 */
32
function text_field_info() {
33
  return array(
34
    'text' => array(
35
      'label' => t('Text'),
36
      'description' => t('This field stores varchar text in the database.'),
37
      'settings' => array('max_length' => 255),
38
      'instance_settings' => array('text_processing' => 0),
39
      'default_widget' => 'text_textfield',
40
      'default_formatter' => 'text_default',
41
    ),
42
    'text_long' => array(
43
      'label' => t('Long text'),
44
      'description' => t('This field stores long text in the database.'),
45
      'instance_settings' => array('text_processing' => 0),
46
      'default_widget' => 'text_textarea',
47
      'default_formatter' => 'text_default',
48
    ),
49
    'text_with_summary' => array(
50
      'label' => t('Long text and summary'),
51
      'description' => t('This field stores long text in the database along with optional summary text.'),
52
      'instance_settings' => array('text_processing' => 1, 'display_summary' => 0),
53
      'default_widget' => 'text_textarea_with_summary',
54
      'default_formatter' => 'text_default',
55
    ),
56
  );
57
}
58

    
59
/**
60
 * Implements hook_field_settings_form().
61
 */
62
function text_field_settings_form($field, $instance, $has_data) {
63
  $settings = $field['settings'];
64

    
65
  $form = array();
66

    
67
  if ($field['type'] == 'text') {
68
    $form['max_length'] = array(
69
      '#type' => 'textfield',
70
      '#title' => t('Maximum length'),
71
      '#default_value' => $settings['max_length'],
72
      '#required' => TRUE,
73
      '#description' => t('The maximum length of the field in characters.'),
74
      '#element_validate' => array('element_validate_integer_positive'),
75
      // @todo: If $has_data, add a validate handler that only allows
76
      // max_length to increase.
77
      '#disabled' => $has_data,
78
    );
79
  }
80

    
81
  return $form;
82
}
83

    
84
/**
85
 * Implements hook_field_instance_settings_form().
86
 */
87
function text_field_instance_settings_form($field, $instance) {
88
  $settings = $instance['settings'];
89

    
90
  $form['text_processing'] = array(
91
    '#type' => 'radios',
92
    '#title' => t('Text processing'),
93
    '#default_value' => $settings['text_processing'],
94
    '#options' => array(
95
      t('Plain text'),
96
      t('Filtered text (user selects text format)'),
97
    ),
98
  );
99
  if ($field['type'] == 'text_with_summary') {
100
    $form['display_summary'] = array(
101
      '#type' => 'checkbox',
102
      '#title' => t('Summary input'),
103
      '#default_value' => $settings['display_summary'],
104
      '#description' => t('This allows authors to input an explicit summary, to be displayed instead of the automatically trimmed text when using the "Summary or trimmed" display type.'),
105
    );
106
  }
107

    
108
  return $form;
109
}
110

    
111
/**
112
 * Implements hook_field_validate().
113
 *
114
 * Possible error codes:
115
 * - 'text_value_max_length': The value exceeds the maximum length.
116
 * - 'text_summary_max_length': The summary exceeds the maximum length.
117
 */
118
function text_field_validate($entity_type, $entity, $field, $instance, $langcode, $items, &$errors) {
119
  foreach ($items as $delta => $item) {
120
    // @todo Length is counted separately for summary and value, so the maximum
121
    //   length can be exceeded very easily.
122
    foreach (array('value', 'summary') as $column) {
123
      if (!empty($item[$column])) {
124
        if (!empty($field['settings']['max_length']) && drupal_strlen($item[$column]) > $field['settings']['max_length']) {
125
          switch ($column) {
126
            case 'value':
127
              $message = t('%name: the text may not be longer than %max characters.', array('%name' => $instance['label'], '%max' => $field['settings']['max_length']));
128
              break;
129

    
130
            case 'summary':
131
              $message = t('%name: the summary may not be longer than %max characters.', array('%name' => $instance['label'], '%max' => $field['settings']['max_length']));
132
              break;
133
          }
134
          $errors[$field['field_name']][$langcode][$delta][] = array(
135
            'error' => "text_{$column}_length",
136
            'message' => $message,
137
          );
138
        }
139
      }
140
    }
141
  }
142
}
143

    
144
/**
145
 * Implements hook_field_load().
146
 *
147
 * Where possible, generate the sanitized version of each field early so that
148
 * it is cached in the field cache. This avoids looking up from the filter cache
149
 * separately.
150
 *
151
 * @see text_field_formatter_view()
152
 */
153
function text_field_load($entity_type, $entities, $field, $instances, $langcode, &$items) {
154
  foreach ($entities as $id => $entity) {
155
    foreach ($items[$id] as $delta => $item) {
156
      // Only process items with a cacheable format, the rest will be handled
157
      // by formatters if needed.
158
      if (empty($instances[$id]['settings']['text_processing']) || filter_format_allowcache($item['format'])) {
159
        $items[$id][$delta]['safe_value'] = isset($item['value']) ? _text_sanitize($instances[$id], $langcode, $item, 'value') : '';
160
        if ($field['type'] == 'text_with_summary') {
161
          $items[$id][$delta]['safe_summary'] = isset($item['summary']) ? _text_sanitize($instances[$id], $langcode, $item, 'summary') : '';
162
        }
163
      }
164
    }
165
  }
166
}
167

    
168
/**
169
 * Implements hook_field_is_empty().
170
 */
171
function text_field_is_empty($item, $field) {
172
  if (!isset($item['value']) || $item['value'] === '') {
173
    return !isset($item['summary']) || $item['summary'] === '';
174
  }
175
  return FALSE;
176
}
177

    
178
/**
179
 * Implements hook_field_formatter_info().
180
 */
181
function text_field_formatter_info() {
182
  return array(
183
    'text_default' => array(
184
      'label' => t('Default'),
185
      'field types' => array('text', 'text_long', 'text_with_summary'),
186
    ),
187
    'text_plain' => array(
188
      'label' => t('Plain text'),
189
      'field types' => array('text', 'text_long', 'text_with_summary'),
190
    ),
191

    
192
    // The text_trimmed formatter displays the trimmed version of the
193
    // full element of the field. It is intended to be used with text
194
    // and text_long fields. It also works with text_with_summary
195
    // fields though the text_summary_or_trimmed formatter makes more
196
    // sense for that field type.
197
    'text_trimmed' => array(
198
      'label' => t('Trimmed'),
199
      'field types' => array('text', 'text_long', 'text_with_summary'),
200
      'settings' => array('trim_length' => 600),
201
    ),
202

    
203
    // The 'summary or trimmed' field formatter for text_with_summary
204
    // fields displays returns the summary element of the field or, if
205
    // the summary is empty, the trimmed version of the full element
206
    // of the field.
207
    'text_summary_or_trimmed' => array(
208
      'label' => t('Summary or trimmed'),
209
      'field types' => array('text_with_summary'),
210
      'settings' => array('trim_length' => 600),
211
    ),
212
  );
213
}
214

    
215
/**
216
 * Implements hook_field_formatter_settings_form().
217
 */
218
function text_field_formatter_settings_form($field, $instance, $view_mode, $form, &$form_state) {
219
  $display = $instance['display'][$view_mode];
220
  $settings = $display['settings'];
221

    
222
  $element = array();
223

    
224
  if (strpos($display['type'], '_trimmed') !== FALSE) {
225
    $element['trim_length'] = array(
226
      '#title' => t('Trim length'),
227
      '#type' => 'textfield',
228
      '#size' => 10,
229
      '#default_value' => $settings['trim_length'],
230
      '#element_validate' => array('element_validate_integer_positive'),
231
      '#required' => TRUE,
232
    );
233
  }
234

    
235
  return $element;
236
}
237

    
238
/**
239
 * Implements hook_field_formatter_settings_summary().
240
 */
241
function text_field_formatter_settings_summary($field, $instance, $view_mode) {
242
  $display = $instance['display'][$view_mode];
243
  $settings = $display['settings'];
244

    
245
  $summary = '';
246

    
247
  if (strpos($display['type'], '_trimmed') !== FALSE) {
248
    $summary = t('Trim length') . ': ' . check_plain($settings['trim_length']);
249
  }
250

    
251
  return $summary;
252
}
253

    
254
/**
255
 * Implements hook_field_formatter_view().
256
 */
257
function text_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
258
  $element = array();
259

    
260
  switch ($display['type']) {
261
    case 'text_default':
262
    case 'text_trimmed':
263
      foreach ($items as $delta => $item) {
264
        $output = _text_sanitize($instance, $langcode, $item, 'value');
265
        if ($display['type'] == 'text_trimmed') {
266
          $output = text_summary($output, $instance['settings']['text_processing'] ? $item['format'] : NULL, $display['settings']['trim_length']);
267
        }
268
        $element[$delta] = array('#markup' => $output);
269
      }
270
      break;
271

    
272
    case 'text_summary_or_trimmed':
273
      foreach ($items as $delta => $item) {
274
        if (!empty($item['summary'])) {
275
          $output = _text_sanitize($instance, $langcode, $item, 'summary');
276
        }
277
        else {
278
          $output = _text_sanitize($instance, $langcode, $item, 'value');
279
          $output = text_summary($output, $instance['settings']['text_processing'] ? $item['format'] : NULL, $display['settings']['trim_length']);
280
        }
281
        $element[$delta] = array('#markup' => $output);
282
      }
283
      break;
284

    
285
    case 'text_plain':
286
      foreach ($items as $delta => $item) {
287
        $element[$delta] = array('#markup' => strip_tags($item['value']));
288
      }
289
      break;
290
  }
291

    
292
  return $element;
293
}
294

    
295
/**
296
 * Sanitizes the 'value' or 'summary' data of a text value.
297
 *
298
 * Depending on whether the field instance uses text processing, data is run
299
 * through check_plain() or check_markup().
300
 *
301
 * @param $instance
302
 *   The instance definition.
303
 * @param $langcode
304
 *  The language associated to $item.
305
 * @param $item
306
 *   The field value to sanitize.
307
 * @param $column
308
 *   The column to sanitize (either 'value' or 'summary').
309
 *
310
 * @return
311
 *  The sanitized string.
312
 */
313
function _text_sanitize($instance, $langcode, $item, $column) {
314
  // If the value uses a cacheable text format, text_field_load() precomputes
315
  // the sanitized string.
316
  if (isset($item["safe_$column"])) {
317
    return $item["safe_$column"];
318
  }
319
  return $instance['settings']['text_processing'] ? check_markup($item[$column], $item['format'], $langcode) : check_plain($item[$column]);
320
}
321

    
322
/**
323
 * Generate a trimmed, formatted version of a text field value.
324
 *
325
 * If the end of the summary is not indicated using the <!--break--> delimiter
326
 * then we generate the summary automatically, trying to end it at a sensible
327
 * place such as the end of a paragraph, a line break, or the end of a
328
 * sentence (in that order of preference).
329
 *
330
 * @param $text
331
 *   The content for which a summary will be generated.
332
 * @param $format
333
 *   The format of the content.
334
 *   If the PHP filter is present and $text contains PHP code, we do not
335
 *   split it up to prevent parse errors.
336
 *   If the line break filter is present then we treat newlines embedded in
337
 *   $text as line breaks.
338
 *   If the htmlcorrector filter is present, it will be run on the generated
339
 *   summary (if different from the incoming $text).
340
 * @param $size
341
 *   The desired character length of the summary. If omitted, the default
342
 *   value will be used. Ignored if the special delimiter is present
343
 *   in $text.
344
 * @return
345
 *   The generated summary.
346
 */
347
function text_summary($text, $format = NULL, $size = NULL) {
348

    
349
  if (!isset($size)) {
350
    // What used to be called 'teaser' is now called 'summary', but
351
    // the variable 'teaser_length' is preserved for backwards compatibility.
352
    $size = variable_get('teaser_length', 600);
353
  }
354

    
355
  // Find where the delimiter is in the body
356
  $delimiter = strpos($text, '<!--break-->');
357

    
358
  // If the size is zero, and there is no delimiter, the entire body is the summary.
359
  if ($size == 0 && $delimiter === FALSE) {
360
    return $text;
361
  }
362

    
363
  // If a valid delimiter has been specified, use it to chop off the summary.
364
  if ($delimiter !== FALSE) {
365
    return substr($text, 0, $delimiter);
366
  }
367

    
368
  // We check for the presence of the PHP evaluator filter in the current
369
  // format. If the body contains PHP code, we do not split it up to prevent
370
  // parse errors.
371
  if (isset($format)) {
372
    $filters = filter_list_format($format);
373
    if (isset($filters['php_code']) && $filters['php_code']->status && strpos($text, '<?') !== FALSE) {
374
      return $text;
375
    }
376
  }
377

    
378
  // If we have a short body, the entire body is the summary.
379
  if (drupal_strlen($text) <= $size) {
380
    return $text;
381
  }
382

    
383
  // If the delimiter has not been specified, try to split at paragraph or
384
  // sentence boundaries.
385

    
386
  // The summary may not be longer than maximum length specified. Initial slice.
387
  $summary = truncate_utf8($text, $size);
388

    
389
  // Store the actual length of the UTF8 string -- which might not be the same
390
  // as $size.
391
  $max_rpos = strlen($summary);
392

    
393
  // How much to cut off the end of the summary so that it doesn't end in the
394
  // middle of a paragraph, sentence, or word.
395
  // Initialize it to maximum in order to find the minimum.
396
  $min_rpos = $max_rpos;
397

    
398
  // Store the reverse of the summary. We use strpos on the reversed needle and
399
  // haystack for speed and convenience.
400
  $reversed = strrev($summary);
401

    
402
  // Build an array of arrays of break points grouped by preference.
403
  $break_points = array();
404

    
405
  // A paragraph near the end of sliced summary is most preferable.
406
  $break_points[] = array('</p>' => 0);
407

    
408
  // If no complete paragraph then treat line breaks as paragraphs.
409
  $line_breaks = array('<br />' => 6, '<br>' => 4);
410
  // Newline only indicates a line break if line break converter
411
  // filter is present.
412
  if (isset($filters['filter_autop'])) {
413
    $line_breaks["\n"] = 1;
414
  }
415
  $break_points[] = $line_breaks;
416

    
417
  // If the first paragraph is too long, split at the end of a sentence.
418
  $break_points[] = array('. ' => 1, '! ' => 1, '? ' => 1, '。' => 0, '؟ ' => 1);
419

    
420
  // Iterate over the groups of break points until a break point is found.
421
  foreach ($break_points as $points) {
422
    // Look for each break point, starting at the end of the summary.
423
    foreach ($points as $point => $offset) {
424
      // The summary is already reversed, but the break point isn't.
425
      $rpos = strpos($reversed, strrev($point));
426
      if ($rpos !== FALSE) {
427
        $min_rpos = min($rpos + $offset, $min_rpos);
428
      }
429
    }
430

    
431
    // If a break point was found in this group, slice and stop searching.
432
    if ($min_rpos !== $max_rpos) {
433
      // Don't slice with length 0. Length must be <0 to slice from RHS.
434
      $summary = ($min_rpos === 0) ? $summary : substr($summary, 0, 0 - $min_rpos);
435
      break;
436
    }
437
  }
438

    
439
  // If the htmlcorrector filter is present, apply it to the generated summary.
440
  if (isset($filters['filter_htmlcorrector'])) {
441
    $summary = _filter_htmlcorrector($summary);
442
  }
443

    
444
  return $summary;
445
}
446

    
447
/**
448
 * Implements hook_field_widget_info().
449
 */
450
function text_field_widget_info() {
451
  return array(
452
    'text_textfield' => array(
453
      'label' => t('Text field'),
454
      'field types' => array('text'),
455
      'settings' => array('size' => 60),
456
    ),
457
    'text_textarea' => array(
458
      'label' => t('Text area (multiple rows)'),
459
      'field types' => array('text_long'),
460
      'settings' => array('rows' => 5),
461
    ),
462
    'text_textarea_with_summary' => array(
463
      'label' => t('Text area with a summary'),
464
      'field types' => array('text_with_summary'),
465
      'settings' => array('rows' => 20, 'summary_rows' => 5),
466
    ),
467
  );
468
}
469

    
470
/**
471
 * Implements hook_field_widget_settings_form().
472
 */
473
function text_field_widget_settings_form($field, $instance) {
474
  $widget = $instance['widget'];
475
  $settings = $widget['settings'];
476

    
477
  if ($widget['type'] == 'text_textfield') {
478
    $form['size'] = array(
479
      '#type' => 'textfield',
480
      '#title' => t('Size of textfield'),
481
      '#default_value' => $settings['size'],
482
      '#required' => TRUE,
483
      '#element_validate' => array('element_validate_integer_positive'),
484
    );
485
  }
486
  else {
487
    $form['rows'] = array(
488
      '#type' => 'textfield',
489
      '#title' => t('Rows'),
490
      '#default_value' => $settings['rows'],
491
      '#required' => TRUE,
492
      '#element_validate' => array('element_validate_integer_positive'),
493
    );
494
  }
495

    
496
  return $form;
497
}
498

    
499
/**
500
 * Implements hook_field_widget_form().
501
 */
502
function text_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) {
503
  $summary_widget = array();
504
  $main_widget = array();
505

    
506
  switch ($instance['widget']['type']) {
507
    case 'text_textfield':
508
      $main_widget = $element + array(
509
        '#type' => 'textfield',
510
        '#default_value' => isset($items[$delta]['value']) ? $items[$delta]['value'] : NULL,
511
        '#size' => $instance['widget']['settings']['size'],
512
        '#maxlength' => $field['settings']['max_length'],
513
        '#attributes' => array('class' => array('text-full')),
514
      );
515
      break;
516

    
517
    case 'text_textarea_with_summary':
518
      $display = !empty($items[$delta]['summary']) || !empty($instance['settings']['display_summary']);
519
      $summary_widget = array(
520
        '#type' => $display ? 'textarea' : 'value',
521
        '#default_value' => isset($items[$delta]['summary']) ? $items[$delta]['summary'] : NULL,
522
        '#title' => t('Summary'),
523
        '#rows' => $instance['widget']['settings']['summary_rows'],
524
        '#description' => t('Leave blank to use trimmed value of full text as the summary.'),
525
        '#attached' => array(
526
          'js' => array(drupal_get_path('module', 'text') . '/text.js'),
527
        ),
528
        '#attributes' => array('class' => array('text-summary')),
529
        '#prefix' => '<div class="text-summary-wrapper">',
530
        '#suffix' => '</div>',
531
        '#weight' => -10,
532
      );
533
      // Fall through to the next case.
534

    
535
    case 'text_textarea':
536
      $main_widget = $element + array(
537
        '#type' => 'textarea',
538
        '#default_value' => isset($items[$delta]['value']) ? $items[$delta]['value'] : NULL,
539
        '#rows' => $instance['widget']['settings']['rows'],
540
        '#attributes' => array('class' => array('text-full')),
541
      );
542
      break;
543
  }
544

    
545
  if ($main_widget) {
546
    // Conditionally alter the form element's type if text processing is enabled.
547
    if ($instance['settings']['text_processing']) {
548
      $element = $main_widget;
549
      $element['#type'] = 'text_format';
550
      $element['#format'] = isset($items[$delta]['format']) ? $items[$delta]['format'] : NULL;
551
      $element['#base_type'] = $main_widget['#type'];
552
    }
553
    else {
554
      $element['value'] = $main_widget;
555
    }
556
  }
557
  if ($summary_widget) {
558
    $element['summary'] = $summary_widget;
559
  }
560

    
561
  return $element;
562
}
563

    
564
/**
565
 * Implements hook_field_widget_error().
566
 */
567
function text_field_widget_error($element, $error, $form, &$form_state) {
568
  switch ($error['error']) {
569
    case 'text_summary_max_length':
570
      $error_element = $element[$element['#columns'][1]];
571
      break;
572

    
573
    default:
574
      $error_element = $element[$element['#columns'][0]];
575
      break;
576
  }
577

    
578
  form_error($error_element, $error['message']);
579
}
580

    
581
/**
582
 * Implements hook_field_prepare_translation().
583
 */
584
function text_field_prepare_translation($entity_type, $entity, $field, $instance, $langcode, &$items, $source_entity, $source_langcode) {
585
  // If the translating user is not permitted to use the assigned text format,
586
  // we must not expose the source values.
587
  $field_name = $field['field_name'];
588
  if (!empty($source_entity->{$field_name}[$source_langcode])) {
589
    $formats = filter_formats();
590
    foreach ($source_entity->{$field_name}[$source_langcode] as $delta => $item) {
591
      $format_id = $item['format'];
592
      if (!empty($format_id) && !filter_access($formats[$format_id])) {
593
        unset($items[$delta]);
594
      }
595
    }
596
  }
597
}
598

    
599
/**
600
 * Implements hook_filter_format_update().
601
 */
602
function text_filter_format_update($format) {
603
  field_cache_clear();
604
}
605

    
606
/**
607
 * Implements hook_filter_format_disable().
608
 */
609
function text_filter_format_disable($format) {
610
  field_cache_clear();
611
}