TextExtHelper.php 12 KB

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