modifier.escape.php 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. <?php
  2. /**
  3. * Smarty plugin
  4. * @package Smarty
  5. * @subpackage plugins
  6. */
  7. /**
  8. * Smarty escape modifier plugin
  9. *
  10. * Type: modifier<br>
  11. * Name: escape<br>
  12. * Purpose: Escape the string according to escapement type
  13. * @link http://smarty.php.net/manual/en/language.modifier.escape.php
  14. * escape (Smarty online manual)
  15. * @param string
  16. * @param html|htmlall|url|quotes|hex|hexentity|javascript
  17. * @return string
  18. */
  19. function smarty_modifier_escape($string, $esc_type = 'html')
  20. {
  21. switch ($esc_type) {
  22. case 'html':
  23. return htmlspecialchars($string, ENT_QUOTES);
  24. case 'htmlall':
  25. return htmlentities($string, ENT_QUOTES);
  26. case 'url':
  27. return urlencode($string);
  28. case 'quotes':
  29. // escape unescaped single quotes
  30. return preg_replace("%(?<!\\\\)'%", "\\'", $string);
  31. case 'hex':
  32. // escape every character into hex
  33. $return = '';
  34. for ($x=0; $x < strlen($string); $x++) {
  35. $return .= '%' . bin2hex($string[$x]);
  36. }
  37. return $return;
  38. case 'hexentity':
  39. $return = '';
  40. for ($x=0; $x < strlen($string); $x++) {
  41. $return .= '&#x' . bin2hex($string[$x]) . ';';
  42. }
  43. return $return;
  44. case 'decentity':
  45. $return = '';
  46. for ($x=0; $x < strlen($string); $x++) {
  47. $return .= '&#' . ord($string[$x]) . ';';
  48. }
  49. return $return;
  50. case 'javascript':
  51. // escape quotes and backslashes, newlines, etc.
  52. return strtr($string, array('\\'=>'\\\\',"'"=>"\\'",'"'=>'\\"',"\r"=>'\\r',"\n"=>'\\n','</'=>'<\/'));
  53. case 'mail':
  54. // safe way to display e-mail address on a web page
  55. return str_replace(array('@', '.'),array(' [AT] ', ' [DOT] '), $string);
  56. case 'nonstd':
  57. // escape non-standard chars, such as ms document quotes
  58. $_res = '';
  59. for($_i = 0, $_len = strlen($string); $_i < $_len; $_i++) {
  60. $_ord = ord($string{$_i});
  61. // non-standard char, escape it
  62. if($_ord >= 126){
  63. $_res .= '&#' . $_ord . ';';
  64. }
  65. else {
  66. $_res .= $string{$_i};
  67. }
  68. }
  69. return $_res;
  70. default:
  71. return $string;
  72. }
  73. }
  74. /* vim: set expandtab: */
  75. ?>