block.textformat.php 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. <?php
  2. /**
  3. * Smarty plugin
  4. * @package Smarty
  5. * @subpackage plugins
  6. */
  7. /**
  8. * Smarty {textformat}{/textformat} block plugin
  9. *
  10. * Type: block function<br>
  11. * Name: textformat<br>
  12. * Purpose: format text a certain way with preset styles
  13. * or custom wrap/indent settings<br>
  14. * @link http://smarty.php.net/manual/en/language.function.textformat.php {textformat}
  15. * (Smarty online manual)
  16. * @param array
  17. * <pre>
  18. * Params: style: string (email)
  19. * indent: integer (0)
  20. * wrap: integer (80)
  21. * wrap_char string ("\n")
  22. * indent_char: string (" ")
  23. * wrap_boundary: boolean (true)
  24. * </pre>
  25. * @param string contents of the block
  26. * @param Smarty clever simulation of a method
  27. * @return string string $content re-formatted
  28. */
  29. function smarty_block_textformat($params, $content, &$smarty)
  30. {
  31. if (is_null($content)) {
  32. return;
  33. }
  34. $style = null;
  35. $indent = 0;
  36. $indent_first = 0;
  37. $indent_char = ' ';
  38. $wrap = 80;
  39. $wrap_char = "\n";
  40. $wrap_cut = false;
  41. $assign = null;
  42. foreach ($params as $_key => $_val) {
  43. switch ($_key) {
  44. case 'style':
  45. case 'indent_char':
  46. case 'wrap_char':
  47. case 'assign':
  48. $$_key = (string)$_val;
  49. break;
  50. case 'indent':
  51. case 'indent_first':
  52. case 'wrap':
  53. $$_key = (int)$_val;
  54. break;
  55. case 'wrap_cut':
  56. $$_key = (bool)$_val;
  57. break;
  58. default:
  59. $smarty->trigger_error("textformat: unknown attribute '$_key'");
  60. }
  61. }
  62. if ($style == 'email') {
  63. $wrap = 72;
  64. }
  65. // split into paragraphs
  66. $_paragraphs = preg_split('![\r\n][\r\n]!',$content);
  67. $_output = '';
  68. for($_x = 0, $_y = count($_paragraphs); $_x < $_y; $_x++) {
  69. if ($_paragraphs[$_x] == '') {
  70. continue;
  71. }
  72. // convert mult. spaces & special chars to single space
  73. $_paragraphs[$_x] = preg_replace(array('!\s+!','!(^\s+)|(\s+$)!'), array(' ',''), $_paragraphs[$_x]);
  74. // indent first line
  75. if($indent_first > 0) {
  76. $_paragraphs[$_x] = str_repeat($indent_char, $indent_first) . $_paragraphs[$_x];
  77. }
  78. // wordwrap sentences
  79. $_paragraphs[$_x] = wordwrap($_paragraphs[$_x], $wrap - $indent, $wrap_char, $wrap_cut);
  80. // indent lines
  81. if($indent > 0) {
  82. $_paragraphs[$_x] = preg_replace('!^!m', str_repeat($indent_char, $indent), $_paragraphs[$_x]);
  83. }
  84. }
  85. $_output = implode($wrap_char . $wrap_char, $_paragraphs);
  86. return $assign ? $smarty->assign($assign, $_output) : $_output;
  87. }
  88. /* vim: set expandtab: */
  89. ?>