TextExtHelper.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381
  1. <?php
  2. App::uses('TextHelper', 'View/Helper');
  3. App::uses('HtmlHelper', 'View/Helper');
  4. App::uses('View', 'View');
  5. /**
  6. * The core text helper is unsecure and outdated in functionality.
  7. * This aims to compensate the deficiencies.
  8. *
  9. * autoLinkEmails
  10. * - obfuscate (defaults to FALSE right now)
  11. * (- maxLength?)
  12. * - escape (defaults to TRUE for security reasons regarding plain text)
  13. *
  14. * autoLinkUrls
  15. * - stripProtocol (defaults To FALSE right now)
  16. * - maxLength (to shorten links in order to not mess up the layout in some cases - appends ...)
  17. * - escape (defaults to TRUE for security reasons regarding plain text)
  18. *
  19. */
  20. class TextExtHelper extends TextHelper {
  21. /**
  22. * Constructor
  23. *
  24. * ### Settings:
  25. *
  26. * - `engine` Class name to use to replace String functionality.
  27. * The class needs to be placed in the `Utility` directory.
  28. *
  29. * @param View $View the view object the helper is attached to.
  30. * @param array $settings Settings array Settings array
  31. * @throws CakeException when the engine class could not be found.
  32. */
  33. public function __construct(View $View, $settings = array()) {
  34. $settings = Hash::merge(array('engine' => 'Tools.TextLib'), $settings);
  35. parent::__construct($View, $settings);
  36. }
  37. /**
  38. * Convert all links and email adresses to HTML links.
  39. *
  40. * @param string $text Text
  41. * @param array $options Array of HTML options.
  42. * @return string The text with links
  43. * @link http://book.cakephp.org/view/1469/Text#autoLink-1620
  44. */
  45. public function autoLink($text, $options = array(), $htmlOptions = array()) {
  46. if (!isset($options['escape']) || $options['escape'] !== false) {
  47. $text = h($text);
  48. $options['escape'] = false;
  49. }
  50. return $this->autoLinkEmails($this->autoLinkUrls($text, $options, $htmlOptions), $options, $htmlOptions);
  51. }
  52. /**
  53. * Fix to allow obfuscation of email (js, img?)
  54. * @param string $text
  55. * @param htmlOptions (additionally - not yet supported by core):
  56. * - obfuscate: true/false (defaults to false)
  57. * @param array $options
  58. * - escape (defaults to true)
  59. * @return string html
  60. * @override
  61. */
  62. public function autoLinkEmails($text, $options = array(), $htmlOptions = array()) {
  63. if (!isset($options['escape']) || $options['escape'] !== false) {
  64. $text = h($text);
  65. }
  66. $linkOptions = 'array(';
  67. foreach ($htmlOptions as $option => $value) {
  68. $value = var_export($value, true);
  69. $linkOptions .= "'$option' => $value, ";
  70. }
  71. $linkOptions .= ')';
  72. $customOptions = 'array(';
  73. foreach ($options as $option => $value) {
  74. $value = var_export($value, true);
  75. $customOptions .= "'$option' => $value, ";
  76. }
  77. $customOptions .= ')';
  78. $atom = '[a-z0-9!#$%&\'*+\/=?^_`{|}~-]';
  79. return preg_replace_callback('/(' . $atom . '+(?:\.' . $atom . '+)*@[a-z0-9-]+(?:\.[a-z0-9-]+)+)/i',
  80. create_function('$matches', 'return TextExtHelper::prepareEmail($matches[0],' . $linkOptions . ',' . $customOptions . ');'), $text);
  81. }
  82. /**
  83. * @param string $email
  84. * @param options:
  85. * - obfuscate: true/false (defaults to false)
  86. * @return string html
  87. */
  88. public static function prepareEmail($email, $options = array(), $customOptions = array()) {
  89. $obfuscate = false;
  90. if (isset($options['obfuscate'])) {
  91. $obfuscate = $options['obfuscate'];
  92. unset($options['obfuscate']);
  93. }
  94. if (!isset($customOptions['escape']) || $customOptions['escape'] !== false) {
  95. $email = hDec($email);
  96. }
  97. $Html = new HtmlHelper(new View(null));
  98. //$Html->tags = $Html->loadConfig();
  99. //debug($Html->tags);
  100. if (!$obfuscate) {
  101. return $Html->link($email, "mailto:" . $email, $options);
  102. }
  103. $class = __CLASS__;
  104. $Common = new $class;
  105. $Common->Html = $Html;
  106. return $Common->encodeEmailUrl($email, null, array(), $options);
  107. }
  108. /**
  109. * Helper Function to Obfuscate Email by inserting a span tag (not more! not very secure on its own...)
  110. * each part of this mail now does not make sense anymore on its own
  111. * (striptags will not work either)
  112. * @param string email: necessary (and valid - containing one @)
  113. * @return string html
  114. */
  115. public function encodeEmail($mail) {
  116. list($mail1, $mail2) = explode('@', $mail);
  117. $encMail = $this->encodeText($mail1) . '<span>@</span>' . $this->encodeText($mail2);
  118. return $encMail;
  119. }
  120. /**
  121. * Obfuscates Email (works without JS!) to avoid lowlevel spam bots to get it
  122. * @param string mail: email to encode
  123. * @param string text: optional (if none is given, email will be text as well)
  124. * @param array attributes: html tag attributes
  125. * @param array params: ?subject=y&body=y to be attached to "mailto:xyz"
  126. * @return string html with js generated link around email (and non js fallback)
  127. */
  128. public function encodeEmailUrl($mail, $text=null, $params=array(), $attr = array()) {
  129. if (empty($class)) {
  130. $class = 'email';
  131. }
  132. $defaults = array(
  133. 'title' => __('for use in an external mail client'),
  134. 'class' => 'email',
  135. 'escape' => false
  136. );
  137. if (empty($text)) {
  138. $text = $this->encodeEmail($mail);
  139. }
  140. $encMail = 'mailto:' . $mail;
  141. //$encMail = $this->encodeText($encMail); # not possible
  142. // additionally there could be a span tag in between: email<span syle="display:none"></span>@web.de
  143. $querystring = '';
  144. foreach ($params as $key => $val) {
  145. if ($querystring) {
  146. $querystring .= "&$key=" . rawurlencode($val);
  147. } else {
  148. $querystring = "?$key=" . rawurlencode($val);
  149. }
  150. }
  151. $attr = array_merge($defaults, $attr);
  152. $xmail = $this->Html->link('', $encMail . $querystring, $attr);
  153. $xmail1 = mb_substr($xmail, 0, count($xmail) - 5);
  154. $xmail2 = mb_substr($xmail, -4, 4);
  155. $len = mb_strlen($xmail1);
  156. $i = 0;
  157. while ($i < $len) {
  158. $c = mt_rand(2, 6);
  159. $par[] = (mb_substr($xmail1, $i, $c));
  160. $i += $c;
  161. }
  162. $join = implode('\'+\'', $par);
  163. return '<script language=javascript><!--
  164. document.write(\'' . $join . '\');
  165. //--></script>
  166. ' . $text . '
  167. <script language=javascript><!--
  168. document.write(\'' . $xmail2 . '\');
  169. //--></script>';
  170. //return '<a class="'.$class.'" title="'.$title.'" href="'.$encmail.$querystring.'">'.$encText.'</a>';
  171. }
  172. /**
  173. * Encodes Piece of Text (without usage of JS!) to avoid lowlevel spam bots to get it
  174. * @param STRING text to encode
  175. * @return string html (randomly encoded)
  176. */
  177. public static function encodeText($text) {
  178. $encmail = '';
  179. $length = mb_strlen($text);
  180. for ($i = 0; $i < $length; $i++) {
  181. $encMod = mt_rand(0, 2);
  182. switch ($encMod) {
  183. case 0: // None
  184. $encmail .= mb_substr($text, $i, 1);
  185. break;
  186. case 1: // Decimal
  187. $encmail .= "&#" . ord(mb_substr($text, $i, 1)) . ';';
  188. break;
  189. case 2: // Hexadecimal
  190. $encmail .= "&#x" . dechex(ord(mb_substr($text, $i, 1))) . ';';
  191. break;
  192. }
  193. }
  194. return $encmail;
  195. }
  196. /**
  197. * Fix to allow shortened urls that do not break layout etc
  198. *
  199. * @param string $text
  200. * @param options (additionally - not yet supported by core):
  201. * - stripProtocol: bool (defaults to true)
  202. * - maxLength: int (defaults no none)
  203. * @param htmlOptions
  204. * - escape etc
  205. * @return string html
  206. * @override
  207. */
  208. public function autoLinkUrls($text, $options = array(), $htmlOptions = array()) {
  209. if (!isset($options['escape']) || $options['escape'] !== false) {
  210. $text = h($text);
  211. $matchString = 'hDec($matches[0])';
  212. } else {
  213. $matchString = '$matches[0]';
  214. }
  215. if (isset($htmlOptions['escape'])) {
  216. $options['escape'] = $htmlOptions['escape'];
  217. }
  218. //$htmlOptions['escape'] = false;
  219. $htmlOptions = var_export($htmlOptions, true);
  220. $customOptions = var_export($options, true);
  221. $text = preg_replace_callback('#(?<!href="|">)((?:https?|ftp|nntp)://[^\s<>()]+)#i', create_function('$matches',
  222. '$Html = new HtmlHelper(new View(null)); return $Html->link(TextExtHelper::prepareLinkName(hDec($matches[0]), ' . $customOptions . '), hDec($matches[0]),' . $htmlOptions . ');'), $text);
  223. return preg_replace_callback('#(?<!href="|">)(?<!http://|https://|ftp://|nntp://)(www\.[^\n\%\ <]+[^<\n\%\,\.\ <])(?<!\))#i',
  224. create_function('$matches', '$Html = new HtmlHelper(new View(null)); return $Html->link(TextExtHelper::prepareLinkName(hDec($matches[0]), ' . $customOptions . '), "http://" . hDec($matches[0]),' . $htmlOptions . ');'), $text);
  225. }
  226. /**
  227. * @param string $link
  228. * @param options:
  229. * - stripProtocol: bool (defaults to true)
  230. * - maxLength: int (defaults to 50)
  231. * - escape (defaults to false, true needed for hellip to work)
  232. * @return string html/$plain
  233. */
  234. public static function prepareLinkName($link, $options = array()) {
  235. # strip protocol if desired (default)
  236. if (!isset($options['stripProtocol']) || $options['stripProtocol'] !== false) {
  237. $link = self::stripProtocol($link);
  238. }
  239. if (!isset($options['maxLength'])) {
  240. $options['maxLength'] = 50; # should be long enough for most cases
  241. }
  242. # shorten display name if desired (default)
  243. if (!empty($options['maxLength']) && mb_strlen($link) > $options['maxLength']) {
  244. $link = mb_substr($link, 0, $options['maxLength']);
  245. # problematic with autoLink()
  246. if (!empty($options['html']) && isset($options['escape']) && $options['escape'] === false) {
  247. $link .= '&hellip;'; # only possible with escape => false!
  248. } else {
  249. $link .= '...';
  250. }
  251. }
  252. return $link;
  253. }
  254. /**
  255. * Remove http:// or other protocols from the link
  256. *
  257. * @param string $url
  258. * @return string strippedUrl
  259. */
  260. public static function stripProtocol($url) {
  261. $pieces = parse_url($url);
  262. if (empty($pieces['scheme'])) {
  263. return $url; # already stripped
  264. }
  265. return mb_substr($url, mb_strlen($pieces['scheme']) + 3); # +3 <=> :// # can only be 4 with "file" (file:///)...
  266. }
  267. /**
  268. * Minimizes the given url to a maximum length
  269. *
  270. * @param string $url the url
  271. * @param integer $max the maximum length
  272. * @param array $options
  273. * - placeholder
  274. * @return string the manipulated url (+ eventuell ...)
  275. */
  276. public function minimizeUrl($url = null, $max = null, $options = array()) {
  277. // check if there is nothing to do
  278. if (empty($url) || mb_strlen($url) <= (int)$max) {
  279. return (string)$url;
  280. }
  281. // http:// has not to be displayed, so
  282. if (mb_substr($url, 0, 7) === 'http://') {
  283. $url = mb_substr($url, 7);
  284. }
  285. // cut the parameters
  286. if (mb_strpos($url, '/') !== false) {
  287. $url = strtok($url, '/');
  288. }
  289. // return if the url is short enough
  290. if (mb_strlen($url) <= (int)$max) {
  291. return $url;
  292. }
  293. // otherwise cut a part in the middle (but only if long enough!!!)
  294. # TODO: more dynamically
  295. $placeholder = CHAR_HELLIP;
  296. if (!empty($options['placeholder'])) {
  297. $placeholder = $options['placeholder'];
  298. }
  299. $end = mb_substr($url, -5, 5);
  300. $front = mb_substr($url, 0, (int)$max - 8);
  301. return $front . $placeholder . $end;
  302. }
  303. /**
  304. * Transforming int values into ordinal numbers (1st, 3rd, etc.)
  305. * @param $num (INT) - the number to be suffixed.
  306. * @param $sup (BOOL) - whether to wrap the suffix in a superscript (<sup>) tag on output.
  307. * @return string ordinal
  308. */
  309. public static function ordinalNumber($num = 0, $sup = false) {
  310. $suff = '';
  311. if (!in_array(($num % 100), array(11, 12, 13))) {
  312. switch ($num % 10) {
  313. case 1:
  314. $suff = 'st';
  315. break;
  316. case 2:
  317. $suff = 'nd';
  318. break;
  319. case 3:
  320. $suff = 'rd';
  321. break;
  322. default:
  323. $suff = 'th';
  324. }
  325. }
  326. return ($sup) ? $num . '<sup>' . $suff . '</sup>' : $num . $suff;
  327. }
  328. /**
  329. * Syntax highlighting using php internal highlighting
  330. * @param string $filename
  331. * @param boolean $return (else echo directly)
  332. */
  333. public static function highlightFile($file, $return = true) {
  334. return highlight_file($file, $return);
  335. }
  336. /**
  337. * Syntax highlighting using php internal highlighting
  338. * @param string $contentstring
  339. * @param boolean $return (else echo directly)
  340. */
  341. public static function highlightString($string, $return = true) {
  342. return highlight_string($string, $return);
  343. }
  344. }