TYPO3 CMS  TYPO3_6-2
JavaScriptEncoder.php
Go to the documentation of this file.
1 <?php
3 
30 
37  protected $hexMatrix = array();
38 
44  protected $immuneCharacters = array(',', '.', '_');
45 
51  protected $charsetConversion = NULL;
52 
58  public function __construct() {
59  $this->charsetConversion = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\Charset\\CharsetConverter');
60  for ($i = 0; $i < 256; $i++) {
61  if ($i >= ord('0') && $i <= ord('9') || $i >= ord('A') && $i <= ord('Z') || $i >= ord('a') && $i <= ord('z')) {
62  $this->hexMatrix[$i] = NULL;
63  } else {
64  $this->hexMatrix[$i] = dechex($i);
65  }
66  }
67  }
68 
75  public function encode($input) {
76  $stringLength = $this->charsetConversion->strlen('utf-8', $input);
77  $encodedString = '';
78  for ($i = 0; $i < $stringLength; $i++) {
79  $c = $this->charsetConversion->substr('utf-8', $input, $i, 1);
80  $encodedString .= $this->encodeCharacter($c);
81  }
82  return $encodedString;
83  }
84 
95  protected function encodeCharacter($character) {
96  if ($this->isImmuneCharacter($character)) {
97  return $character;
98  }
99  $ordinalValue = $this->charsetConversion->utf8CharToUnumber($character);
100  // Check for alphanumeric characters
101  $hex = $this->getHexForNonAlphanumeric($ordinalValue);
102  if ($hex === NULL) {
103  return $character;
104  }
105  // Encode up to 256 with \\xHH
106  if ($ordinalValue < 256) {
107  $pad = substr('00', strlen($hex));
108  return '\\x' . $pad . strtoupper($hex);
109  }
110  // Otherwise encode with \\uHHHH
111  $pad = substr('0000', strlen($hex));
112  return '\\u' . $pad . strtoupper($hex);
113  }
114 
121  protected function isImmuneCharacter($character) {
122  return in_array($character, $this->immuneCharacters, TRUE);
123  }
124 
135  protected function getHexForNonAlphanumeric($ordinalValue) {
136  if ($ordinalValue <= 255) {
137  return $this->hexMatrix[$ordinalValue];
138  }
139  return dechex($ordinalValue);
140  }
141 
142 }