PageRenderTime 590ms CodeModel.GetById 26ms RepoModel.GetById 0ms app.codeStats 0ms

/lib/Cake/View/Helper/TextHelper.php

https://bitbucket.org/udeshika/fake_twitter
PHP | 376 lines | 203 code | 34 blank | 139 comment | 36 complexity | 94fe2724bd25ecbae265a3e3cfba5b91 MD5 | raw file
  1. <?php
  2. /**
  3. * Text Helper
  4. *
  5. * Text manipulations: Highlight, excerpt, truncate, strip of links, convert email addresses to mailto: links...
  6. *
  7. * PHP 5
  8. *
  9. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  10. * Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
  11. *
  12. * Licensed under The MIT License
  13. * Redistributions of files must retain the above copyright notice.
  14. *
  15. * @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
  16. * @link http://cakephp.org CakePHP(tm) Project
  17. * @package Cake.View.Helper
  18. * @since CakePHP(tm) v 0.10.0.1076
  19. * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
  20. */
  21. App::uses('AppHelper', 'View/Helper');
  22. App::uses('HtmlHelper', 'Helper');
  23. App::uses('Multibyte', 'I18n');
  24. /**
  25. * Text helper library.
  26. *
  27. * Text manipulations: Highlight, excerpt, truncate, strip of links, convert email addresses to mailto: links...
  28. *
  29. * @package Cake.View.Helper
  30. * @property HtmlHelper $Html
  31. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/text.html
  32. */
  33. class TextHelper extends AppHelper {
  34. /**
  35. * helpers
  36. *
  37. * @var array
  38. */
  39. public $helpers = array('Html');
  40. /**
  41. * Highlights a given phrase in a text. You can specify any expression in highlighter that
  42. * may include the \1 expression to include the $phrase found.
  43. *
  44. * ### Options:
  45. *
  46. * - `format` The piece of html with that the phrase will be highlighted
  47. * - `html` If true, will ignore any HTML tags, ensuring that only the correct text is highlighted
  48. *
  49. * @param string $text Text to search the phrase in
  50. * @param string $phrase The phrase that will be searched
  51. * @param array $options An array of html attributes and options.
  52. * @return string The highlighted text
  53. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/text.html#TextHelper::highlight
  54. */
  55. public function highlight($text, $phrase, $options = array()) {
  56. if (empty($phrase)) {
  57. return $text;
  58. }
  59. $default = array(
  60. 'format' => '<span class="highlight">\1</span>',
  61. 'html' => false
  62. );
  63. $options = array_merge($default, $options);
  64. extract($options);
  65. if (is_array($phrase)) {
  66. $replace = array();
  67. $with = array();
  68. foreach ($phrase as $key => $segment) {
  69. $segment = '(' . preg_quote($segment, '|') . ')';
  70. if ($html) {
  71. $segment = "(?![^<]+>)$segment(?![^<]+>)";
  72. }
  73. $with[] = (is_array($format)) ? $format[$key] : $format;
  74. $replace[] = "|$segment|iu";
  75. }
  76. return preg_replace($replace, $with, $text);
  77. } else {
  78. $phrase = '(' . preg_quote($phrase, '|') . ')';
  79. if ($html) {
  80. $phrase = "(?![^<]+>)$phrase(?![^<]+>)";
  81. }
  82. return preg_replace("|$phrase|iu", $format, $text);
  83. }
  84. }
  85. /**
  86. * Strips given text of all links (<a href=....)
  87. *
  88. * @param string $text Text
  89. * @return string The text without links
  90. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/text.html#TextHelper::stripLinks
  91. */
  92. public function stripLinks($text) {
  93. return preg_replace('|<a\s+[^>]+>|im', '', preg_replace('|<\/a>|im', '', $text));
  94. }
  95. /**
  96. * Adds links (<a href=....) to a given text, by finding text that begins with
  97. * strings like http:// and ftp://.
  98. *
  99. * @param string $text Text to add links to
  100. * @param array $htmlOptions Array of HTML options.
  101. * @return string The text with links
  102. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/text.html#TextHelper::autoLinkUrls
  103. */
  104. public function autoLinkUrls($text, $htmlOptions = array()) {
  105. $this->_linkOptions = $htmlOptions;
  106. $text = preg_replace_callback(
  107. '#(?<!href="|src="|">)((?:https?|ftp|nntp)://[^\s<>()]+)#i',
  108. array(&$this, '_linkBareUrl'),
  109. $text
  110. );
  111. return preg_replace_callback(
  112. '#(?<!href="|">)(?<!http://|https://|ftp://|nntp://)(www\.[^\n\%\ <]+[^<\n\%\,\.\ <])(?<!\))#i',
  113. array(&$this, '_linkUrls'),
  114. $text
  115. );
  116. }
  117. /**
  118. * Links urls that include http://
  119. *
  120. * @param array $matches
  121. * @return string
  122. * @see TextHelper::autoLinkUrls()
  123. */
  124. protected function _linkBareUrl($matches) {
  125. return $this->Html->link($matches[0], $matches[0], $this->_linkOptions);
  126. }
  127. /**
  128. * Links urls missing http://
  129. *
  130. * @param array $matches
  131. * @return string
  132. * @see TextHelper::autoLinkUrls()
  133. */
  134. protected function _linkUrls($matches) {
  135. return $this->Html->link($matches[0], 'http://' . $matches[0], $this->_linkOptions);
  136. }
  137. /**
  138. * Links email addresses
  139. *
  140. * @param array $matches
  141. * @return string
  142. * @see TextHelper::autoLinkUrls()
  143. */
  144. protected function _linkEmails($matches) {
  145. return $this->Html->link($matches[0], 'mailto:' . $matches[0], $this->_linkOptions);
  146. }
  147. /**
  148. * Adds email links (<a href="mailto:....) to a given text.
  149. *
  150. * @param string $text Text
  151. * @param array $options Array of HTML options.
  152. * @return string The text with links
  153. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/text.html#TextHelper::autoLinkEmails
  154. */
  155. public function autoLinkEmails($text, $options = array()) {
  156. $this->_linkOptions = $options;
  157. $atom = '[a-z0-9!#$%&\'*+\/=?^_`{|}~-]';
  158. return preg_replace_callback(
  159. '/(' . $atom . '+(?:\.' . $atom . '+)*@[a-z0-9-]+(?:\.[a-z0-9-]+)+)/i',
  160. array(&$this, '_linkEmails'),
  161. $text
  162. );
  163. }
  164. /**
  165. * Convert all links and email addresses to HTML links.
  166. *
  167. * @param string $text Text
  168. * @param array $options Array of HTML options.
  169. * @return string The text with links
  170. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/text.html#TextHelper::autoLink
  171. */
  172. public function autoLink($text, $options = array()) {
  173. return $this->autoLinkEmails($this->autoLinkUrls($text, $options), $options);
  174. }
  175. /**
  176. * Truncates text.
  177. *
  178. * Cuts a string to the length of $length and replaces the last characters
  179. * with the ending if the text is longer than length.
  180. *
  181. * ### Options:
  182. *
  183. * - `ending` Will be used as Ending and appended to the trimmed string
  184. * - `exact` If false, $text will not be cut mid-word
  185. * - `html` If true, HTML tags would be handled correctly
  186. *
  187. * @param string $text String to truncate.
  188. * @param integer $length Length of returned string, including ellipsis.
  189. * @param array $options An array of html attributes and options.
  190. * @return string Trimmed string.
  191. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/text.html#TextHelper::truncate
  192. */
  193. public function truncate($text, $length = 100, $options = array()) {
  194. $default = array(
  195. 'ending' => '...', 'exact' => true, 'html' => false
  196. );
  197. $options = array_merge($default, $options);
  198. extract($options);
  199. if (!function_exists('mb_strlen')) {
  200. class_exists('Multibyte');
  201. }
  202. if ($html) {
  203. if (mb_strlen(preg_replace('/<.*?>/', '', $text)) <= $length) {
  204. return $text;
  205. }
  206. $totalLength = mb_strlen(strip_tags($ending));
  207. $openTags = array();
  208. $truncate = '';
  209. preg_match_all('/(<\/?([\w+]+)[^>]*>)?([^<>]*)/', $text, $tags, PREG_SET_ORDER);
  210. foreach ($tags as $tag) {
  211. if (!preg_match('/img|br|input|hr|area|base|basefont|col|frame|isindex|link|meta|param/s', $tag[2])) {
  212. if (preg_match('/<[\w]+[^>]*>/s', $tag[0])) {
  213. array_unshift($openTags, $tag[2]);
  214. } else if (preg_match('/<\/([\w]+)[^>]*>/s', $tag[0], $closeTag)) {
  215. $pos = array_search($closeTag[1], $openTags);
  216. if ($pos !== false) {
  217. array_splice($openTags, $pos, 1);
  218. }
  219. }
  220. }
  221. $truncate .= $tag[1];
  222. $contentLength = mb_strlen(preg_replace('/&[0-9a-z]{2,8};|&#[0-9]{1,7};|&#x[0-9a-f]{1,6};/i', ' ', $tag[3]));
  223. if ($contentLength + $totalLength > $length) {
  224. $left = $length - $totalLength;
  225. $entitiesLength = 0;
  226. if (preg_match_all('/&[0-9a-z]{2,8};|&#[0-9]{1,7};|&#x[0-9a-f]{1,6};/i', $tag[3], $entities, PREG_OFFSET_CAPTURE)) {
  227. foreach ($entities[0] as $entity) {
  228. if ($entity[1] + 1 - $entitiesLength <= $left) {
  229. $left--;
  230. $entitiesLength += mb_strlen($entity[0]);
  231. } else {
  232. break;
  233. }
  234. }
  235. }
  236. $truncate .= mb_substr($tag[3], 0 , $left + $entitiesLength);
  237. break;
  238. } else {
  239. $truncate .= $tag[3];
  240. $totalLength += $contentLength;
  241. }
  242. if ($totalLength >= $length) {
  243. break;
  244. }
  245. }
  246. } else {
  247. if (mb_strlen($text) <= $length) {
  248. return $text;
  249. } else {
  250. $truncate = mb_substr($text, 0, $length - mb_strlen($ending));
  251. }
  252. }
  253. if (!$exact) {
  254. $spacepos = mb_strrpos($truncate, ' ');
  255. if ($html) {
  256. $truncateCheck = mb_substr($truncate, 0, $spacepos);
  257. $lastOpenTag = mb_strrpos($truncateCheck, '<');
  258. $lastCloseTag = mb_strrpos($truncateCheck, '>');
  259. if ($lastOpenTag > $lastCloseTag) {
  260. preg_match_all('/<[\w]+[^>]*>/s', $truncate, $lastTagMatches);
  261. $lastTag = array_pop($lastTagMatches[0]);
  262. $spacepos = mb_strrpos($truncate, $lastTag) + mb_strlen($lastTag);
  263. }
  264. $bits = mb_substr($truncate, $spacepos);
  265. preg_match_all('/<\/([a-z]+)>/', $bits, $droppedTags, PREG_SET_ORDER);
  266. if (!empty($droppedTags)) {
  267. if (!empty($openTags)) {
  268. foreach ($droppedTags as $closingTag) {
  269. if (!in_array($closingTag[1], $openTags)) {
  270. array_unshift($openTags, $closingTag[1]);
  271. }
  272. }
  273. } else {
  274. foreach ($droppedTags as $closingTag) {
  275. array_push($openTags, $closingTag[1]);
  276. }
  277. }
  278. }
  279. }
  280. $truncate = mb_substr($truncate, 0, $spacepos);
  281. }
  282. $truncate .= $ending;
  283. if ($html) {
  284. foreach ($openTags as $tag) {
  285. $truncate .= '</' . $tag . '>';
  286. }
  287. }
  288. return $truncate;
  289. }
  290. /**
  291. * Extracts an excerpt from the text surrounding the phrase with a number of characters on each side
  292. * determined by radius.
  293. *
  294. * @param string $text String to search the phrase in
  295. * @param string $phrase Phrase that will be searched for
  296. * @param integer $radius The amount of characters that will be returned on each side of the founded phrase
  297. * @param string $ending Ending that will be appended
  298. * @return string Modified string
  299. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/text.html#TextHelper::excerpt
  300. */
  301. public function excerpt($text, $phrase, $radius = 100, $ending = '...') {
  302. if (empty($text) or empty($phrase)) {
  303. return $this->truncate($text, $radius * 2, array('ending' => $ending));
  304. }
  305. $append = $prepend = $ending;
  306. $phraseLen = mb_strlen($phrase);
  307. $textLen = mb_strlen($text);
  308. $pos = mb_strpos(mb_strtolower($text), mb_strtolower($phrase));
  309. if ($pos === false) {
  310. return mb_substr($text, 0, $radius) . $ending;
  311. }
  312. $startPos = $pos - $radius;
  313. if ($startPos <= 0) {
  314. $startPos = 0;
  315. $prepend = '';
  316. }
  317. $endPos = $pos + $phraseLen + $radius;
  318. if ($endPos >= $textLen) {
  319. $endPos = $textLen;
  320. $append = '';
  321. }
  322. $excerpt = mb_substr($text, $startPos, $endPos - $startPos);
  323. $excerpt = $prepend . $excerpt . $append;
  324. return $excerpt;
  325. }
  326. /**
  327. * Creates a comma separated list where the last two items are joined with 'and', forming natural English
  328. *
  329. * @param array $list The list to be joined
  330. * @param string $and The word used to join the last and second last items together with. Defaults to 'and'
  331. * @param string $separator The separator used to join all the other items together. Defaults to ', '
  332. * @return string The glued together string.
  333. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/text.html#TextHelper::toList
  334. */
  335. public function toList($list, $and = 'and', $separator = ', ') {
  336. if (count($list) > 1) {
  337. return implode($separator, array_slice($list, null, -1)) . ' ' . $and . ' ' . array_pop($list);
  338. } else {
  339. return array_pop($list);
  340. }
  341. }
  342. }