text.module

You are here

  1. 7 modules/field/modules/text/text.module
  2. 8 core/modules/field/modules/text/text.module
  3. 8 core/modules/text/text.module

Defines simple text field types.

Functions

File

modules/field/modules/text/text.module
View source
  1. <?php
  2. /**
  3. * @file
  4. * Defines simple text field types.
  5. */
  6. /**
  7. * Implements hook_help().
  8. */
  9. function text_help($path, $arg) {
  10. switch ($path) {
  11. case 'admin/help#text':
  12. $output = '';
  13. $output .= '<h3>' . t('About') . '</h3>';
  14. $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>';
  15. return $output;
  16. }
  17. }
  18. /**
  19. * Implements hook_field_info().
  20. *
  21. * Field settings:
  22. * - max_length: the maximum length for a varchar field.
  23. * Instance settings:
  24. * - text_processing: whether text input filters should be used.
  25. * - display_summary: whether the summary field should be displayed.
  26. * When empty and not displayed the summary will take its value from the
  27. * trimmed value of the main text field.
  28. */
  29. function text_field_info() {
  30. return array(
  31. 'text' => array(
  32. 'label' => t('Text'),
  33. 'description' => t('This field stores varchar text in the database.'),
  34. 'settings' => array('max_length' => 255),
  35. 'instance_settings' => array('text_processing' => 0),
  36. 'default_widget' => 'text_textfield',
  37. 'default_formatter' => 'text_default',
  38. ),
  39. 'text_long' => array(
  40. 'label' => t('Long text'),
  41. 'description' => t('This field stores long text in the database.'),
  42. 'instance_settings' => array('text_processing' => 0),
  43. 'default_widget' => 'text_textarea',
  44. 'default_formatter' => 'text_default',
  45. ),
  46. 'text_with_summary' => array(
  47. 'label' => t('Long text and summary'),
  48. 'description' => t('This field stores long text in the database along with optional summary text.'),
  49. 'instance_settings' => array('text_processing' => 1, 'display_summary' => 0),
  50. 'default_widget' => 'text_textarea_with_summary',
  51. 'default_formatter' => 'text_default',
  52. ),
  53. );
  54. }
  55. /**
  56. * Implements hook_field_settings_form().
  57. */
  58. function text_field_settings_form($field, $instance, $has_data) {
  59. $settings = $field['settings'];
  60. $form = array();
  61. if ($field['type'] == 'text') {
  62. $form['max_length'] = array(
  63. '#type' => 'textfield',
  64. '#title' => t('Maximum length'),
  65. '#default_value' => $settings['max_length'],
  66. '#required' => TRUE,
  67. '#description' => t('The maximum length of the field in characters.'),
  68. '#element_validate' => array('element_validate_integer_positive'),
  69. // @todo: If $has_data, add a validate handler that only allows
  70. // max_length to increase.
  71. '#disabled' => $has_data,
  72. );
  73. }
  74. return $form;
  75. }
  76. /**
  77. * Implements hook_field_instance_settings_form().
  78. */
  79. function text_field_instance_settings_form($field, $instance) {
  80. $settings = $instance['settings'];
  81. $form['text_processing'] = array(
  82. '#type' => 'radios',
  83. '#title' => t('Text processing'),
  84. '#default_value' => $settings['text_processing'],
  85. '#options' => array(
  86. t('Plain text'),
  87. t('Filtered text (user selects text format)'),
  88. ),
  89. );
  90. if ($field['type'] == 'text_with_summary') {
  91. $form['display_summary'] = array(
  92. '#type' => 'checkbox',
  93. '#title' => t('Summary input'),
  94. '#default_value' => $settings['display_summary'],
  95. '#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.'),
  96. );
  97. }
  98. return $form;
  99. }
  100. /**
  101. * Implements hook_field_validate().
  102. *
  103. * Possible error codes:
  104. * - 'text_value_max_length': The value exceeds the maximum length.
  105. * - 'text_summary_max_length': The summary exceeds the maximum length.
  106. */
  107. function text_field_validate($entity_type, $entity, $field, $instance, $langcode, $items, &$errors) {
  108. foreach ($items as $delta => $item) {
  109. // @todo Length is counted separately for summary and value, so the maximum
  110. // length can be exceeded very easily.
  111. foreach (array('value', 'summary') as $column) {
  112. if (!empty($item[$column])) {
  113. if (!empty($field['settings']['max_length']) && drupal_strlen($item[$column]) > $field['settings']['max_length']) {
  114. switch ($column) {
  115. case 'value':
  116. $message = t('%name: the text may not be longer than %max characters.', array('%name' => $instance['label'], '%max' => $field['settings']['max_length']));
  117. break;
  118. case 'summary':
  119. $message = t('%name: the summary may not be longer than %max characters.', array('%name' => $instance['label'], '%max' => $field['settings']['max_length']));
  120. break;
  121. }
  122. $errors[$field['field_name']][$langcode][$delta][] = array(
  123. 'error' => "text_{$column}_length",
  124. 'message' => $message,
  125. );
  126. }
  127. }
  128. }
  129. }
  130. }
  131. /**
  132. * Implements hook_field_load().
  133. *
  134. * Where possible, generate the sanitized version of each field early so that
  135. * it is cached in the field cache. This avoids looking up from the filter cache
  136. * separately.
  137. *
  138. * @see text_field_formatter_view()
  139. */
  140. function text_field_load($entity_type, $entities, $field, $instances, $langcode, &$items) {
  141. foreach ($entities as $id => $entity) {
  142. foreach ($items[$id] as $delta => $item) {
  143. // Only process items with a cacheable format, the rest will be handled
  144. // by formatters if needed.
  145. if (empty($instances[$id]['settings']['text_processing']) || filter_format_allowcache($item['format'])) {
  146. $items[$id][$delta]['safe_value'] = isset($item['value']) ? _text_sanitize($instances[$id], $langcode, $item, 'value') : '';
  147. if ($field['type'] == 'text_with_summary') {
  148. $items[$id][$delta]['safe_summary'] = isset($item['summary']) ? _text_sanitize($instances[$id], $langcode, $item, 'summary') : '';
  149. }
  150. }
  151. }
  152. }
  153. }
  154. /**
  155. * Implements hook_field_is_empty().
  156. */
  157. function text_field_is_empty($item, $field) {
  158. if (!isset($item['value']) || $item['value'] === '') {
  159. return !isset($item['summary']) || $item['summary'] === '';
  160. }
  161. return FALSE;
  162. }
  163. /**
  164. * Implements hook_field_formatter_info().
  165. */
  166. function text_field_formatter_info() {
  167. return array(
  168. 'text_default' => array(
  169. 'label' => t('Default'),
  170. 'field types' => array('text', 'text_long', 'text_with_summary'),
  171. ),
  172. 'text_plain' => array(
  173. 'label' => t('Plain text'),
  174. 'field types' => array('text', 'text_long', 'text_with_summary'),
  175. ),
  176. // The text_trimmed formatter displays the trimmed version of the
  177. // full element of the field. It is intended to be used with text
  178. // and text_long fields. It also works with text_with_summary
  179. // fields though the text_summary_or_trimmed formatter makes more
  180. // sense for that field type.
  181. 'text_trimmed' => array(
  182. 'label' => t('Trimmed'),
  183. 'field types' => array('text', 'text_long', 'text_with_summary'),
  184. 'settings' => array('trim_length' => 600),
  185. ),
  186. // The 'summary or trimmed' field formatter for text_with_summary
  187. // fields displays returns the summary element of the field or, if
  188. // the summary is empty, the trimmed version of the full element
  189. // of the field.
  190. 'text_summary_or_trimmed' => array(
  191. 'label' => t('Summary or trimmed'),
  192. 'field types' => array('text_with_summary'),
  193. 'settings' => array('trim_length' => 600),
  194. ),
  195. );
  196. }
  197. /**
  198. * Implements hook_field_formatter_settings_form().
  199. */
  200. function text_field_formatter_settings_form($field, $instance, $view_mode, $form, &$form_state) {
  201. $display = $instance['display'][$view_mode];
  202. $settings = $display['settings'];
  203. $element = array();
  204. if (strpos($display['type'], '_trimmed') !== FALSE) {
  205. $element['trim_length'] = array(
  206. '#title' => t('Trim length'),
  207. '#type' => 'textfield',
  208. '#size' => 10,
  209. '#default_value' => $settings['trim_length'],
  210. '#element_validate' => array('element_validate_integer_positive'),
  211. '#required' => TRUE,
  212. );
  213. }
  214. return $element;
  215. }
  216. /**
  217. * Implements hook_field_formatter_settings_summary().
  218. */
  219. function text_field_formatter_settings_summary($field, $instance, $view_mode) {
  220. $display = $instance['display'][$view_mode];
  221. $settings = $display['settings'];
  222. $summary = '';
  223. if (strpos($display['type'], '_trimmed') !== FALSE) {
  224. $summary = t('Trim length') . ': ' . $settings['trim_length'];
  225. }
  226. return $summary;
  227. }
  228. /**
  229. * Implements hook_field_formatter_view().
  230. */
  231. function text_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
  232. $element = array();
  233. switch ($display['type']) {
  234. case 'text_default':
  235. case 'text_trimmed':
  236. foreach ($items as $delta => $item) {
  237. $output = _text_sanitize($instance, $langcode, $item, 'value');
  238. if ($display['type'] == 'text_trimmed') {
  239. $output = text_summary($output, $instance['settings']['text_processing'] ? $item['format'] : NULL, $display['settings']['trim_length']);
  240. }
  241. $element[$delta] = array('#markup' => $output);
  242. }
  243. break;
  244. case 'text_summary_or_trimmed':
  245. foreach ($items as $delta => $item) {
  246. if (!empty($item['summary'])) {
  247. $output = _text_sanitize($instance, $langcode, $item, 'summary');
  248. }
  249. else {
  250. $output = _text_sanitize($instance, $langcode, $item, 'value');
  251. $output = text_summary($output, $instance['settings']['text_processing'] ? $item['format'] : NULL, $display['settings']['trim_length']);
  252. }
  253. $element[$delta] = array('#markup' => $output);
  254. }
  255. break;
  256. case 'text_plain':
  257. foreach ($items as $delta => $item) {
  258. $element[$delta] = array('#markup' => strip_tags($item['value']));
  259. }
  260. break;
  261. }
  262. return $element;
  263. }
  264. /**
  265. * Sanitizes the 'value' or 'summary' data of a text value.
  266. *
  267. * Depending on whether the field instance uses text processing, data is run
  268. * through check_plain() or check_markup().
  269. *
  270. * @param $instance
  271. * The instance definition.
  272. * @param $langcode
  273. * The language associated to $item.
  274. * @param $item
  275. * The field value to sanitize.
  276. * @param $column
  277. * The column to sanitize (either 'value' or 'summary').
  278. *
  279. * @return
  280. * The sanitized string.
  281. */
  282. function _text_sanitize($instance, $langcode, $item, $column) {
  283. // If the value uses a cacheable text format, text_field_load() precomputes
  284. // the sanitized string.
  285. if (isset($item["safe_$column"])) {
  286. return $item["safe_$column"];
  287. }
  288. return $instance['settings']['text_processing'] ? check_markup($item[$column], $item['format'], $langcode) : check_plain($item[$column]);
  289. }
  290. /**
  291. * Generate a trimmed, formatted version of a text field value.
  292. *
  293. * If the end of the summary is not indicated using the <!--break--> delimiter
  294. * then we generate the summary automatically, trying to end it at a sensible
  295. * place such as the end of a paragraph, a line break, or the end of a
  296. * sentence (in that order of preference).
  297. *
  298. * @param $text
  299. * The content for which a summary will be generated.
  300. * @param $format
  301. * The format of the content.
  302. * If the PHP filter is present and $text contains PHP code, we do not
  303. * split it up to prevent parse errors.
  304. * If the line break filter is present then we treat newlines embedded in
  305. * $text as line breaks.
  306. * If the htmlcorrector filter is present, it will be run on the generated
  307. * summary (if different from the incoming $text).
  308. * @param $size
  309. * The desired character length of the summary. If omitted, the default
  310. * value will be used. Ignored if the special delimiter is present
  311. * in $text.
  312. * @return
  313. * The generated summary.
  314. */
  315. function text_summary($text, $format = NULL, $size = NULL) {
  316. if (!isset($size)) {
  317. // What used to be called 'teaser' is now called 'summary', but
  318. // the variable 'teaser_length' is preserved for backwards compatibility.
  319. $size = variable_get('teaser_length', 600);
  320. }
  321. // Find where the delimiter is in the body
  322. $delimiter = strpos($text, '<!--break-->');
  323. // If the size is zero, and there is no delimiter, the entire body is the summary.
  324. if ($size == 0 && $delimiter === FALSE) {
  325. return $text;
  326. }
  327. // If a valid delimiter has been specified, use it to chop off the summary.
  328. if ($delimiter !== FALSE) {
  329. return substr($text, 0, $delimiter);
  330. }
  331. // We check for the presence of the PHP evaluator filter in the current
  332. // format. If the body contains PHP code, we do not split it up to prevent
  333. // parse errors.
  334. if (isset($format)) {
  335. $filters = filter_list_format($format);
  336. if (isset($filters['php_code']) && $filters['php_code']->status && strpos($text, '<?') !== FALSE) {
  337. return $text;
  338. }
  339. }
  340. // If we have a short body, the entire body is the summary.
  341. if (drupal_strlen($text) <= $size) {
  342. return $text;
  343. }
  344. // If the delimiter has not been specified, try to split at paragraph or
  345. // sentence boundaries.
  346. // The summary may not be longer than maximum length specified. Initial slice.
  347. $summary = truncate_utf8($text, $size);
  348. // Store the actual length of the UTF8 string -- which might not be the same
  349. // as $size.
  350. $max_rpos = strlen($summary);
  351. // How much to cut off the end of the summary so that it doesn't end in the
  352. // middle of a paragraph, sentence, or word.
  353. // Initialize it to maximum in order to find the minimum.
  354. $min_rpos = $max_rpos;
  355. // Store the reverse of the summary. We use strpos on the reversed needle and
  356. // haystack for speed and convenience.
  357. $reversed = strrev($summary);
  358. // Build an array of arrays of break points grouped by preference.
  359. $break_points = array();
  360. // A paragraph near the end of sliced summary is most preferable.
  361. $break_points[] = array('</p>' => 0);
  362. // If no complete paragraph then treat line breaks as paragraphs.
  363. $line_breaks = array('<br />' => 6, '<br>' => 4);
  364. // Newline only indicates a line break if line break converter
  365. // filter is present.
  366. if (isset($filters['filter_autop'])) {
  367. $line_breaks["\n"] = 1;
  368. }
  369. $break_points[] = $line_breaks;
  370. // If the first paragraph is too long, split at the end of a sentence.
  371. $break_points[] = array('. ' => 1, '! ' => 1, '? ' => 1, '。' => 0, '؟ ' => 1);
  372. // Iterate over the groups of break points until a break point is found.
  373. foreach ($break_points as $points) {
  374. // Look for each break point, starting at the end of the summary.
  375. foreach ($points as $point => $offset) {
  376. // The summary is already reversed, but the break point isn't.
  377. $rpos = strpos($reversed, strrev($point));
  378. if ($rpos !== FALSE) {
  379. $min_rpos = min($rpos + $offset, $min_rpos);
  380. }
  381. }
  382. // If a break point was found in this group, slice and stop searching.
  383. if ($min_rpos !== $max_rpos) {
  384. // Don't slice with length 0. Length must be <0 to slice from RHS.
  385. $summary = ($min_rpos === 0) ? $summary : substr($summary, 0, 0 - $min_rpos);
  386. break;
  387. }
  388. }
  389. // If the htmlcorrector filter is present, apply it to the generated summary.
  390. if (isset($filters['filter_htmlcorrector'])) {
  391. $summary = _filter_htmlcorrector($summary);
  392. }
  393. return $summary;
  394. }
  395. /**
  396. * Implements hook_field_widget_info().
  397. */
  398. function text_field_widget_info() {
  399. return array(
  400. 'text_textfield' => array(
  401. 'label' => t('Text field'),
  402. 'field types' => array('text'),
  403. 'settings' => array('size' => 60),
  404. ),
  405. 'text_textarea' => array(
  406. 'label' => t('Text area (multiple rows)'),
  407. 'field types' => array('text_long'),
  408. 'settings' => array('rows' => 5),
  409. ),
  410. 'text_textarea_with_summary' => array(
  411. 'label' => t('Text area with a summary'),
  412. 'field types' => array('text_with_summary'),
  413. 'settings' => array('rows' => 20, 'summary_rows' => 5),
  414. ),
  415. );
  416. }
  417. /**
  418. * Implements hook_field_widget_settings_form().
  419. */
  420. function text_field_widget_settings_form($field, $instance) {
  421. $widget = $instance['widget'];
  422. $settings = $widget['settings'];
  423. if ($widget['type'] == 'text_textfield') {
  424. $form['size'] = array(
  425. '#type' => 'textfield',
  426. '#title' => t('Size of textfield'),
  427. '#default_value' => $settings['size'],
  428. '#required' => TRUE,
  429. '#element_validate' => array('element_validate_integer_positive'),
  430. );
  431. }
  432. else {
  433. $form['rows'] = array(
  434. '#type' => 'textfield',
  435. '#title' => t('Rows'),
  436. '#default_value' => $settings['rows'],
  437. '#required' => TRUE,
  438. '#element_validate' => array('element_validate_integer_positive'),
  439. );
  440. }
  441. return $form;
  442. }
  443. /**
  444. * Implements hook_field_widget_form().
  445. */
  446. function text_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) {
  447. $summary_widget = array();
  448. $main_widget = array();
  449. switch ($instance['widget']['type']) {
  450. case 'text_textfield':
  451. $main_widget = $element + array(
  452. '#type' => 'textfield',
  453. '#default_value' => isset($items[$delta]['value']) ? $items[$delta]['value'] : NULL,
  454. '#size' => $instance['widget']['settings']['size'],
  455. '#maxlength' => $field['settings']['max_length'],
  456. '#attributes' => array('class' => array('text-full')),
  457. );
  458. break;
  459. case 'text_textarea_with_summary':
  460. $display = !empty($items[$delta]['summary']) || !empty($instance['settings']['display_summary']);
  461. $summary_widget = array(
  462. '#type' => $display ? 'textarea' : 'value',
  463. '#default_value' => isset($items[$delta]['summary']) ? $items[$delta]['summary'] : NULL,
  464. '#title' => t('Summary'),
  465. '#rows' => $instance['widget']['settings']['summary_rows'],
  466. '#description' => t('Leave blank to use trimmed value of full text as the summary.'),
  467. '#attached' => array(
  468. 'js' => array(drupal_get_path('module', 'text') . '/text.js'),
  469. ),
  470. '#attributes' => array('class' => array('text-summary')),
  471. '#prefix' => '<div class="text-summary-wrapper">',
  472. '#suffix' => '</div>',
  473. '#weight' => -10,
  474. );
  475. // Fall through to the next case.
  476. case 'text_textarea':
  477. $main_widget = $element + array(
  478. '#type' => 'textarea',
  479. '#default_value' => isset($items[$delta]['value']) ? $items[$delta]['value'] : NULL,
  480. '#rows' => $instance['widget']['settings']['rows'],
  481. '#attributes' => array('class' => array('text-full')),
  482. );
  483. break;
  484. }
  485. if ($main_widget) {
  486. // Conditionally alter the form element's type if text processing is enabled.
  487. if ($instance['settings']['text_processing']) {
  488. $element = $main_widget;
  489. $element['#type'] = 'text_format';
  490. $element['#format'] = isset($items[$delta]['format']) ? $items[$delta]['format'] : NULL;
  491. $element['#base_type'] = $main_widget['#type'];
  492. }
  493. else {
  494. $element['value'] = $main_widget;
  495. }
  496. }
  497. if ($summary_widget) {
  498. $element['summary'] = $summary_widget;
  499. }
  500. return $element;
  501. }
  502. /**
  503. * Implements hook_field_widget_error().
  504. */
  505. function text_field_widget_error($element, $error, $form, &$form_state) {
  506. switch ($error['error']) {
  507. case 'text_summary_max_length':
  508. $error_element = $element[$element['#columns'][1]];
  509. break;
  510. default:
  511. $error_element = $element[$element['#columns'][0]];
  512. break;
  513. }
  514. form_error($error_element, $error['message']);
  515. }
  516. /**
  517. * Implements hook_field_prepare_translation().
  518. */
  519. function text_field_prepare_translation($entity_type, $entity, $field, $instance, $langcode, &$items, $source_entity, $source_langcode) {
  520. // If the translating user is not permitted to use the assigned text format,
  521. // we must not expose the source values.
  522. $field_name = $field['field_name'];
  523. if (!empty($source_entity->{$field_name}[$source_langcode])) {
  524. $formats = filter_formats();
  525. foreach ($source_entity->{$field_name}[$source_langcode] as $delta => $item) {
  526. $format_id = $item['format'];
  527. if (!empty($format_id) && !filter_access($formats[$format_id])) {
  528. unset($items[$delta]);
  529. }
  530. }
  531. }
  532. }
  533. /**
  534. * Implements hook_filter_format_update().
  535. */
  536. function text_filter_format_update($format) {
  537. field_cache_clear();
  538. }
  539. /**
  540. * Implements hook_filter_format_disable().
  541. */
  542. function text_filter_format_disable($format) {
  543. field_cache_clear();
  544. }