TextExtHelper.php 12 KB

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