TextHelper.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324
  1. <?php
  2. /**
  3. * Text Helper
  4. *
  5. * Text manipulations: Highlight, excerpt, truncate, strip of links, convert email addresses to mailto: links...
  6. *
  7. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  8. * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  9. *
  10. * Licensed under The MIT License
  11. * For full copyright and license information, please see the LICENSE.txt
  12. * Redistributions of files must retain the above copyright notice.
  13. *
  14. * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  15. * @link http://cakephp.org CakePHP(tm) Project
  16. * @package Cake.View.Helper
  17. * @since CakePHP(tm) v 0.10.0.1076
  18. * @license http://www.opensource.org/licenses/mit-license.php MIT License
  19. */
  20. App::uses('AppHelper', 'View/Helper');
  21. App::uses('Hash', 'Utility');
  22. /**
  23. * Text helper library.
  24. *
  25. * Text manipulations: Highlight, excerpt, truncate, strip of links, convert email addresses to mailto: links...
  26. *
  27. * @package Cake.View.Helper
  28. * @property HtmlHelper $Html
  29. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/text.html
  30. * @see String
  31. */
  32. class TextHelper extends AppHelper {
  33. /**
  34. * helpers
  35. *
  36. * @var array
  37. */
  38. public $helpers = array('Html');
  39. /**
  40. * An array of md5sums and their contents.
  41. * Used when inserting links into text.
  42. *
  43. * @var array
  44. */
  45. protected $_placeholders = array();
  46. /**
  47. * String utility instance
  48. *
  49. * @var stdClass
  50. */
  51. protected $_engine;
  52. /**
  53. * Constructor
  54. *
  55. * ### Settings:
  56. *
  57. * - `engine` Class name to use to replace String functionality.
  58. * The class needs to be placed in the `Utility` directory.
  59. *
  60. * @param View $View the view object the helper is attached to.
  61. * @param array $settings Settings array Settings array
  62. * @throws CakeException when the engine class could not be found.
  63. */
  64. public function __construct(View $View, $settings = array()) {
  65. $settings = Hash::merge(array('engine' => 'String'), $settings);
  66. parent::__construct($View, $settings);
  67. list($plugin, $engineClass) = pluginSplit($settings['engine'], true);
  68. App::uses($engineClass, $plugin . 'Utility');
  69. if (class_exists($engineClass)) {
  70. $this->_engine = new $engineClass($settings);
  71. } else {
  72. throw new CakeException(__d('cake_dev', '%s could not be found', $engineClass));
  73. }
  74. }
  75. /**
  76. * Call methods from String utility class
  77. * @return mixed Whatever is returned by called method, or false on failure
  78. */
  79. public function __call($method, $params) {
  80. return call_user_func_array(array($this->_engine, $method), $params);
  81. }
  82. /**
  83. * Adds links (<a href=....) to a given text, by finding text that begins with
  84. * strings like http:// and ftp://.
  85. *
  86. * ### Options
  87. *
  88. * - `escape` Control HTML escaping of input. Defaults to true.
  89. *
  90. * @param string $text Text
  91. * @param array $options Array of HTML options, and options listed above.
  92. * @return string The text with links
  93. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/text.html#TextHelper::autoLinkUrls
  94. */
  95. public function autoLinkUrls($text, $options = array()) {
  96. $this->_placeholders = array();
  97. $options += array('escape' => true);
  98. $pattern = '#(?<!href="|src="|">)((?:https?|ftp|nntp)://[\p{L}0-9.\-_:]+(?:[/?][^\s<]*)?)#ui';
  99. $text = preg_replace_callback(
  100. $pattern,
  101. array(&$this, '_insertPlaceHolder'),
  102. $text
  103. );
  104. $text = preg_replace_callback(
  105. '#(?<!href="|">)(?<!\b[[:punct:]])(?<!http://|https://|ftp://|nntp://)www.[^\n\%\ <]+[^<\n\%\,\.\ <](?<!\))#i',
  106. array(&$this, '_insertPlaceHolder'),
  107. $text
  108. );
  109. if ($options['escape']) {
  110. $text = h($text);
  111. }
  112. return $this->_linkUrls($text, $options);
  113. }
  114. /**
  115. * Saves the placeholder for a string, for later use. This gets around double
  116. * escaping content in URL's.
  117. *
  118. * @param array $matches An array of regexp matches.
  119. * @return string Replaced values.
  120. */
  121. protected function _insertPlaceHolder($matches) {
  122. $key = md5($matches[0]);
  123. $this->_placeholders[$key] = $matches[0];
  124. return $key;
  125. }
  126. /**
  127. * Replace placeholders with links.
  128. *
  129. * @param string $text The text to operate on.
  130. * @param array $htmlOptions The options for the generated links.
  131. * @return string The text with links inserted.
  132. */
  133. protected function _linkUrls($text, $htmlOptions) {
  134. $replace = array();
  135. foreach ($this->_placeholders as $hash => $url) {
  136. $link = $url;
  137. if (!preg_match('#^[a-z]+\://#', $url)) {
  138. $url = 'http://' . $url;
  139. }
  140. $replace[$hash] = $this->Html->link($link, $url, $htmlOptions);
  141. }
  142. return strtr($text, $replace);
  143. }
  144. /**
  145. * Links email addresses
  146. *
  147. * @param string $text The text to operate on
  148. * @param array $options An array of options to use for the HTML.
  149. * @return string
  150. * @see TextHelper::autoLinkEmails()
  151. */
  152. protected function _linkEmails($text, $options) {
  153. $replace = array();
  154. foreach ($this->_placeholders as $hash => $url) {
  155. $replace[$hash] = $this->Html->link($url, 'mailto:' . $url, $options);
  156. }
  157. return strtr($text, $replace);
  158. }
  159. /**
  160. * Adds email links (<a href="mailto:....) to a given text.
  161. *
  162. * ### Options
  163. *
  164. * - `escape` Control HTML escaping of input. Defaults to true.
  165. *
  166. * @param string $text Text
  167. * @param array $options Array of HTML options, and options listed above.
  168. * @return string The text with links
  169. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/text.html#TextHelper::autoLinkEmails
  170. */
  171. public function autoLinkEmails($text, $options = array()) {
  172. $options += array('escape' => true);
  173. $this->_placeholders = array();
  174. $atom = '[\p{L}0-9!#$%&\'*+\/=?^_`{|}~-]';
  175. $text = preg_replace_callback(
  176. '/(?<=\s|^|\()(' . $atom . '*(?:\.' . $atom . '+)*@[\p{L}0-9-]+(?:\.[\p{L}0-9-]+)+)/ui',
  177. array(&$this, '_insertPlaceholder'),
  178. $text
  179. );
  180. if ($options['escape']) {
  181. $text = h($text);
  182. }
  183. return $this->_linkEmails($text, $options);
  184. }
  185. /**
  186. * Convert all links and email addresses to HTML links.
  187. *
  188. * ### Options
  189. *
  190. * - `escape` Control HTML escaping of input. Defaults to true.
  191. *
  192. * @param string $text Text
  193. * @param array $options Array of HTML options, and options listed above.
  194. * @return string The text with links
  195. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/text.html#TextHelper::autoLink
  196. */
  197. public function autoLink($text, $options = array()) {
  198. $text = $this->autoLinkUrls($text, $options);
  199. return $this->autoLinkEmails($text, array_merge($options, array('escape' => false)));
  200. }
  201. /**
  202. * Highlights a given phrase in a text. You can specify any expression in highlighter that
  203. * may include the \1 expression to include the $phrase found.
  204. *
  205. * @see String::highlight()
  206. *
  207. * @param string $text Text to search the phrase in
  208. * @param string $phrase The phrase that will be searched
  209. * @param array $options An array of html attributes and options.
  210. * @return string The highlighted text
  211. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/text.html#TextHelper::highlight
  212. */
  213. public function highlight($text, $phrase, $options = array()) {
  214. return $this->_engine->highlight($text, $phrase, $options);
  215. }
  216. /**
  217. * Formats paragraphs around given text for all line breaks
  218. * <br /> added for single line return
  219. * <p> added for double line return
  220. *
  221. * @param string $text Text
  222. * @return string The text with proper <p> and <br /> tags
  223. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/text.html#TextHelper::autoParagraph
  224. */
  225. public function autoParagraph($text) {
  226. if (trim($text) !== '') {
  227. $text = preg_replace('|<br[^>]*>\s*<br[^>]*>|i', "\n\n", $text . "\n");
  228. $text = preg_replace("/\n\n+/", "\n\n", str_replace(array("\r\n", "\r"), "\n", $text));
  229. $texts = preg_split('/\n\s*\n/', $text, -1, PREG_SPLIT_NO_EMPTY);
  230. $text = '';
  231. foreach ($texts as $txt) {
  232. $text .= '<p>' . nl2br(trim($txt, "\n")) . "</p>\n";
  233. }
  234. $text = preg_replace('|<p>\s*</p>|', '', $text);
  235. }
  236. return $text;
  237. }
  238. /**
  239. * Strips given text of all links (<a href=....)
  240. *
  241. * @see String::stripLinks()
  242. *
  243. * @param string $text Text
  244. * @return string The text without links
  245. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/text.html#TextHelper::stripLinks
  246. */
  247. public function stripLinks($text) {
  248. return $this->_engine->stripLinks($text);
  249. }
  250. /**
  251. * Truncates text starting from the end.
  252. *
  253. * Cuts a string to the length of $length and replaces the first characters
  254. * with the ellipsis if the text is longer than length.
  255. *
  256. * ### Options:
  257. *
  258. * - `ellipsis` Will be used as Beginning and prepended to the trimmed string
  259. * - `exact` If false, $text will not be cut mid-word
  260. *
  261. * @see String::truncate()
  262. *
  263. * @param string $text String to truncate.
  264. * @param integer $length Length of returned string, including ellipsis.
  265. * @param array $options An array of html attributes and options.
  266. * @return string Trimmed string.
  267. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/text.html#TextHelper::truncate
  268. */
  269. public function truncate($text, $length = 100, $options = array()) {
  270. return $this->_engine->truncate($text, $length, $options);
  271. }
  272. /**
  273. * Extracts an excerpt from the text surrounding the phrase with a number of characters on each side
  274. * determined by radius.
  275. *
  276. * @see String::excerpt()
  277. *
  278. * @param string $text String to search the phrase in
  279. * @param string $phrase Phrase that will be searched for
  280. * @param integer $radius The amount of characters that will be returned on each side of the founded phrase
  281. * @param string $ending Ending that will be appended
  282. * @return string Modified string
  283. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/text.html#TextHelper::excerpt
  284. */
  285. public function excerpt($text, $phrase, $radius = 100, $ending = '...') {
  286. return $this->_engine->excerpt($text, $phrase, $radius, $ending);
  287. }
  288. /**
  289. * Creates a comma separated list where the last two items are joined with 'and', forming natural English
  290. *
  291. * @see String::toList()
  292. *
  293. * @param array $list The list to be joined
  294. * @param string $and The word used to join the last and second last items together with. Defaults to 'and'
  295. * @param string $separator The separator used to join all the other items together. Defaults to ', '
  296. * @return string The glued together string.
  297. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/text.html#TextHelper::toList
  298. */
  299. public function toList($list, $and = 'and', $separator = ', ') {
  300. return $this->_engine->toList($list, $and, $separator);
  301. }
  302. }