TextExtHelper.php 12 KB

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