TextHelper.php 11 KB

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