TextExtHelper.php 11 KB

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