text.module 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613
  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('Trimmed limit'),
  207. '#type' => 'textfield',
  208. '#field_suffix' => t('characters'),
  209. '#size' => 10,
  210. '#default_value' => $settings['trim_length'],
  211. '#element_validate' => array('element_validate_integer_positive'),
  212. '#description' => t('If the summary is not set, the trimmed %label field will be shorter than this character limit.', array('%label' => $instance['label'])),
  213. '#required' => TRUE,
  214. );
  215. }
  216. return $element;
  217. }
  218. /**
  219. * Implements hook_field_formatter_settings_summary().
  220. */
  221. function text_field_formatter_settings_summary($field, $instance, $view_mode) {
  222. $display = $instance['display'][$view_mode];
  223. $settings = $display['settings'];
  224. $summary = '';
  225. if (strpos($display['type'], '_trimmed') !== FALSE) {
  226. $summary = t('Trimmed limit: @trim_length characters', array('@trim_length' => $settings['trim_length']));
  227. }
  228. return $summary;
  229. }
  230. /**
  231. * Implements hook_field_formatter_view().
  232. */
  233. function text_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
  234. $element = array();
  235. switch ($display['type']) {
  236. case 'text_default':
  237. case 'text_trimmed':
  238. foreach ($items as $delta => $item) {
  239. $output = _text_sanitize($instance, $langcode, $item, 'value');
  240. if ($display['type'] == 'text_trimmed') {
  241. $output = text_summary($output, $instance['settings']['text_processing'] ? $item['format'] : NULL, $display['settings']['trim_length']);
  242. }
  243. $element[$delta] = array('#markup' => $output);
  244. }
  245. break;
  246. case 'text_summary_or_trimmed':
  247. foreach ($items as $delta => $item) {
  248. if (!empty($item['summary'])) {
  249. $output = _text_sanitize($instance, $langcode, $item, 'summary');
  250. }
  251. else {
  252. $output = _text_sanitize($instance, $langcode, $item, 'value');
  253. $output = text_summary($output, $instance['settings']['text_processing'] ? $item['format'] : NULL, $display['settings']['trim_length']);
  254. }
  255. $element[$delta] = array('#markup' => $output);
  256. }
  257. break;
  258. case 'text_plain':
  259. foreach ($items as $delta => $item) {
  260. $element[$delta] = array('#markup' => strip_tags($item['value']));
  261. }
  262. break;
  263. }
  264. return $element;
  265. }
  266. /**
  267. * Sanitizes the 'value' or 'summary' data of a text value.
  268. *
  269. * Depending on whether the field instance uses text processing, data is run
  270. * through check_plain() or check_markup().
  271. *
  272. * @param $instance
  273. * The instance definition.
  274. * @param $langcode
  275. * The language associated to $item.
  276. * @param $item
  277. * The field value to sanitize.
  278. * @param $column
  279. * The column to sanitize (either 'value' or 'summary').
  280. *
  281. * @return
  282. * The sanitized string.
  283. */
  284. function _text_sanitize($instance, $langcode, $item, $column) {
  285. // If the value uses a cacheable text format, text_field_load() precomputes
  286. // the sanitized string.
  287. if (isset($item["safe_$column"])) {
  288. return $item["safe_$column"];
  289. }
  290. return $instance['settings']['text_processing'] ? check_markup($item[$column], $item['format'], $langcode) : check_plain($item[$column]);
  291. }
  292. /**
  293. * Generate a trimmed, formatted version of a text field value.
  294. *
  295. * If the end of the summary is not indicated using the <!--break--> delimiter
  296. * then we generate the summary automatically, trying to end it at a sensible
  297. * place such as the end of a paragraph, a line break, or the end of a
  298. * sentence (in that order of preference).
  299. *
  300. * @param $text
  301. * The content for which a summary will be generated.
  302. * @param $format
  303. * The format of the content.
  304. * If the PHP filter is present and $text contains PHP code, we do not
  305. * split it up to prevent parse errors.
  306. * If the line break filter is present then we treat newlines embedded in
  307. * $text as line breaks.
  308. * If the htmlcorrector filter is present, it will be run on the generated
  309. * summary (if different from the incoming $text).
  310. * @param $size
  311. * The desired character length of the summary. If omitted, the default
  312. * value will be used. Ignored if the special delimiter is present
  313. * in $text.
  314. * @return
  315. * The generated summary.
  316. */
  317. function text_summary($text, $format = NULL, $size = NULL) {
  318. if (!isset($size)) {
  319. // What used to be called 'teaser' is now called 'summary', but
  320. // the variable 'teaser_length' is preserved for backwards compatibility.
  321. $size = variable_get('teaser_length', 600);
  322. }
  323. // Find where the delimiter is in the body
  324. $delimiter = strpos($text, '<!--break-->');
  325. // If the size is zero, and there is no delimiter, the entire body is the summary.
  326. if ($size == 0 && $delimiter === FALSE) {
  327. return $text;
  328. }
  329. // If a valid delimiter has been specified, use it to chop off the summary.
  330. if ($delimiter !== FALSE) {
  331. return substr($text, 0, $delimiter);
  332. }
  333. // We check for the presence of the PHP evaluator filter in the current
  334. // format. If the body contains PHP code, we do not split it up to prevent
  335. // parse errors.
  336. if (isset($format)) {
  337. $filters = filter_list_format($format);
  338. if (isset($filters['php_code']) && $filters['php_code']->status && strpos($text, '<?') !== FALSE) {
  339. return $text;
  340. }
  341. }
  342. // If we have a short body, the entire body is the summary.
  343. if (drupal_strlen($text) <= $size) {
  344. return $text;
  345. }
  346. // If the delimiter has not been specified, try to split at paragraph or
  347. // sentence boundaries.
  348. // The summary may not be longer than maximum length specified. Initial slice.
  349. $summary = truncate_utf8($text, $size);
  350. // Store the actual length of the UTF8 string -- which might not be the same
  351. // as $size.
  352. $max_rpos = strlen($summary);
  353. // How much to cut off the end of the summary so that it doesn't end in the
  354. // middle of a paragraph, sentence, or word.
  355. // Initialize it to maximum in order to find the minimum.
  356. $min_rpos = $max_rpos;
  357. // Store the reverse of the summary. We use strpos on the reversed needle and
  358. // haystack for speed and convenience.
  359. $reversed = strrev($summary);
  360. // Build an array of arrays of break points grouped by preference.
  361. $break_points = array();
  362. // A paragraph near the end of sliced summary is most preferable.
  363. $break_points[] = array('</p>' => 0);
  364. // If no complete paragraph then treat line breaks as paragraphs.
  365. $line_breaks = array('<br />' => 6, '<br>' => 4);
  366. // Newline only indicates a line break if line break converter
  367. // filter is present.
  368. if (isset($filters['filter_autop'])) {
  369. $line_breaks["\n"] = 1;
  370. }
  371. $break_points[] = $line_breaks;
  372. // If the first paragraph is too long, split at the end of a sentence.
  373. $break_points[] = array('. ' => 1, '! ' => 1, '? ' => 1, '。' => 0, '؟ ' => 1);
  374. // Iterate over the groups of break points until a break point is found.
  375. foreach ($break_points as $points) {
  376. // Look for each break point, starting at the end of the summary.
  377. foreach ($points as $point => $offset) {
  378. // The summary is already reversed, but the break point isn't.
  379. $rpos = strpos($reversed, strrev($point));
  380. if ($rpos !== FALSE) {
  381. $min_rpos = min($rpos + $offset, $min_rpos);
  382. }
  383. }
  384. // If a break point was found in this group, slice and stop searching.
  385. if ($min_rpos !== $max_rpos) {
  386. // Don't slice with length 0. Length must be <0 to slice from RHS.
  387. $summary = ($min_rpos === 0) ? $summary : substr($summary, 0, 0 - $min_rpos);
  388. break;
  389. }
  390. }
  391. // If the htmlcorrector filter is present, apply it to the generated summary.
  392. if (isset($filters['filter_htmlcorrector'])) {
  393. $summary = _filter_htmlcorrector($summary);
  394. }
  395. return $summary;
  396. }
  397. /**
  398. * Implements hook_field_widget_info().
  399. */
  400. function text_field_widget_info() {
  401. return array(
  402. 'text_textfield' => array(
  403. 'label' => t('Text field'),
  404. 'field types' => array('text'),
  405. 'settings' => array('size' => 60),
  406. ),
  407. 'text_textarea' => array(
  408. 'label' => t('Text area (multiple rows)'),
  409. 'field types' => array('text_long'),
  410. 'settings' => array('rows' => 5),
  411. ),
  412. 'text_textarea_with_summary' => array(
  413. 'label' => t('Text area with a summary'),
  414. 'field types' => array('text_with_summary'),
  415. 'settings' => array('rows' => 20, 'summary_rows' => 5),
  416. ),
  417. );
  418. }
  419. /**
  420. * Implements hook_field_widget_settings_form().
  421. */
  422. function text_field_widget_settings_form($field, $instance) {
  423. $widget = $instance['widget'];
  424. $settings = $widget['settings'];
  425. if ($widget['type'] == 'text_textfield') {
  426. $form['size'] = array(
  427. '#type' => 'textfield',
  428. '#title' => t('Size of textfield'),
  429. '#default_value' => $settings['size'],
  430. '#required' => TRUE,
  431. '#element_validate' => array('element_validate_integer_positive'),
  432. );
  433. }
  434. else {
  435. $form['rows'] = array(
  436. '#type' => 'textfield',
  437. '#title' => t('Rows'),
  438. '#default_value' => $settings['rows'],
  439. '#required' => TRUE,
  440. '#element_validate' => array('element_validate_integer_positive'),
  441. );
  442. }
  443. return $form;
  444. }
  445. /**
  446. * Implements hook_field_widget_form().
  447. */
  448. function text_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) {
  449. $summary_widget = array();
  450. $main_widget = array();
  451. switch ($instance['widget']['type']) {
  452. case 'text_textfield':
  453. $main_widget = $element + array(
  454. '#type' => 'textfield',
  455. '#default_value' => isset($items[$delta]['value']) ? $items[$delta]['value'] : NULL,
  456. '#size' => $instance['widget']['settings']['size'],
  457. '#maxlength' => $field['settings']['max_length'],
  458. '#attributes' => array('class' => array('text-full')),
  459. );
  460. break;
  461. case 'text_textarea_with_summary':
  462. $display = !empty($items[$delta]['summary']) || !empty($instance['settings']['display_summary']);
  463. $summary_widget = array(
  464. '#type' => $display ? 'textarea' : 'value',
  465. '#default_value' => isset($items[$delta]['summary']) ? $items[$delta]['summary'] : NULL,
  466. '#title' => t('Summary'),
  467. '#rows' => $instance['widget']['settings']['summary_rows'],
  468. '#description' => t('Leave blank to use trimmed value of full text as the summary.'),
  469. '#attached' => array(
  470. 'js' => array(drupal_get_path('module', 'text') . '/text.js'),
  471. ),
  472. '#attributes' => array('class' => array('text-summary')),
  473. '#prefix' => '<div class="text-summary-wrapper">',
  474. '#suffix' => '</div>',
  475. '#weight' => -10,
  476. );
  477. // Fall through to the next case.
  478. case 'text_textarea':
  479. $main_widget = $element + array(
  480. '#type' => 'textarea',
  481. '#default_value' => isset($items[$delta]['value']) ? $items[$delta]['value'] : NULL,
  482. '#rows' => $instance['widget']['settings']['rows'],
  483. '#attributes' => array('class' => array('text-full')),
  484. );
  485. break;
  486. }
  487. if ($main_widget) {
  488. // Conditionally alter the form element's type if text processing is enabled.
  489. if ($instance['settings']['text_processing']) {
  490. $element = $main_widget;
  491. $element['#type'] = 'text_format';
  492. $element['#format'] = isset($items[$delta]['format']) ? $items[$delta]['format'] : NULL;
  493. $element['#base_type'] = $main_widget['#type'];
  494. }
  495. else {
  496. $element['value'] = $main_widget;
  497. }
  498. }
  499. if ($summary_widget) {
  500. $element['summary'] = $summary_widget;
  501. }
  502. return $element;
  503. }
  504. /**
  505. * Implements hook_field_widget_error().
  506. */
  507. function text_field_widget_error($element, $error, $form, &$form_state) {
  508. switch ($error['error']) {
  509. case 'text_summary_max_length':
  510. $error_element = $element[$element['#columns'][1]];
  511. break;
  512. default:
  513. $error_element = $element[$element['#columns'][0]];
  514. break;
  515. }
  516. form_error($error_element, $error['message']);
  517. }
  518. /**
  519. * Implements hook_field_prepare_translation().
  520. */
  521. function text_field_prepare_translation($entity_type, $entity, $field, $instance, $langcode, &$items, $source_entity, $source_langcode) {
  522. // If the translating user is not permitted to use the assigned text format,
  523. // we must not expose the source values.
  524. $field_name = $field['field_name'];
  525. if (!empty($source_entity->{$field_name}[$source_langcode])) {
  526. $formats = filter_formats();
  527. foreach ($source_entity->{$field_name}[$source_langcode] as $delta => $item) {
  528. $format_id = $item['format'];
  529. if (!empty($format_id) && !filter_access($formats[$format_id])) {
  530. unset($items[$delta]);
  531. }
  532. }
  533. }
  534. }
  535. /**
  536. * Implements hook_filter_format_update().
  537. */
  538. function text_filter_format_update($format) {
  539. field_cache_clear();
  540. }
  541. /**
  542. * Implements hook_filter_format_disable().
  543. */
  544. function text_filter_format_disable($format) {
  545. field_cache_clear();
  546. }