TextHelper.php 9.3 KB

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