TextHelper.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412
  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\Core\Exception\Exception;
  18. use Cake\View\Helper;
  19. use Cake\View\View;
  20. /**
  21. * Text helper library.
  22. *
  23. * Text manipulations: Highlight, excerpt, truncate, strip of links, convert email addresses to mailto: links...
  24. *
  25. * @property \Cake\View\Helper\HtmlHelper $Html
  26. * @link http://book.cakephp.org/3.0/en/views/helpers/text.html
  27. * @see \Cake\Utility\Text
  28. */
  29. class TextHelper extends Helper
  30. {
  31. /**
  32. * helpers
  33. *
  34. * @var array
  35. */
  36. public $helpers = ['Html'];
  37. /**
  38. * Default config for this class
  39. *
  40. * @var array
  41. */
  42. protected $_defaultConfig = [
  43. 'engine' => 'Cake\Utility\Text'
  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 = [];
  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 \Cake\View\View $View the view object the helper is attached to.
  67. * @param array $config Settings array Settings array
  68. * @throws \Cake\Core\Exception\Exception when the engine class could not be found.
  69. */
  70. public function __construct(View $View, array $config = [])
  71. {
  72. parent::__construct($View, $config);
  73. $config = $this->_config;
  74. $engineClass = App::className($config['engine'], 'Utility');
  75. if ($engineClass) {
  76. $this->_engine = new $engineClass($config);
  77. } else {
  78. throw new Exception(sprintf('Class for %s could not be found', $config['engine']));
  79. }
  80. }
  81. /**
  82. * Call methods from String utility class
  83. *
  84. * @param string $method Method to invoke
  85. * @param array $params Array of params for the method.
  86. * @return mixed Whatever is returned by called method, or false on failure
  87. */
  88. public function __call($method, $params)
  89. {
  90. return call_user_func_array([$this->_engine, $method], $params);
  91. }
  92. /**
  93. * Adds links (<a href=....) to a given text, by finding text that begins with
  94. * strings like http:// and ftp://.
  95. *
  96. * ### Options
  97. *
  98. * - `escape` Control HTML escaping of input. Defaults to true.
  99. *
  100. * @param string $text Text
  101. * @param array $options Array of HTML options, and options listed above.
  102. * @return string The text with links
  103. * @link http://book.cakephp.org/3.0/en/views/helpers/text.html#linking-urls
  104. */
  105. public function autoLinkUrls($text, array $options = [])
  106. {
  107. $this->_placeholders = [];
  108. $options += ['escape' => true];
  109. $pattern = '/(?:(?<!href="|src="|">)
  110. (?>
  111. (
  112. (?<left>[\[<(]) # left paren,brace
  113. (?>
  114. # Lax match URL
  115. (?<url>(?:https?|ftp|nntp):\/\/[\p{L}0-9.\-_:]+(?:[\/?][\p{L}0-9.\-_:\/?=&>\[\]()#@\+~%]+)?)
  116. (?<right>[\])>]) # right paren,brace
  117. )
  118. )
  119. |
  120. (?<url_bare>(?P>url)) # A bare URL. Use subroutine
  121. )
  122. )/ixu';
  123. $text = preg_replace_callback(
  124. $pattern,
  125. [&$this, '_insertPlaceHolder'],
  126. $text
  127. );
  128. $text = preg_replace_callback(
  129. '#(?<!href="|">)(?<!\b[[:punct:]])(?<!http://|https://|ftp://|nntp://)www\.[^\s\n\%\ <]+[^\s<\n\%\,\.\ <](?<!\))#i',
  130. [&$this, '_insertPlaceHolder'],
  131. $text
  132. );
  133. if ($options['escape']) {
  134. $text = h($text);
  135. }
  136. return $this->_linkUrls($text, $options);
  137. }
  138. /**
  139. * Saves the placeholder for a string, for later use. This gets around double
  140. * escaping content in URL's.
  141. *
  142. * @param array $matches An array of regexp matches.
  143. * @return string Replaced values.
  144. */
  145. protected function _insertPlaceHolder($matches)
  146. {
  147. $match = $matches[0];
  148. $envelope = ['', ''];
  149. if (isset($matches['url'])) {
  150. $match = $matches['url'];
  151. $envelope = [$matches['left'], $matches['right']];
  152. }
  153. if (isset($matches['url_bare'])) {
  154. $match = $matches['url_bare'];
  155. }
  156. $key = md5($match);
  157. $this->_placeholders[$key] = [
  158. 'content' => $match,
  159. 'envelope' => $envelope
  160. ];
  161. return $key;
  162. }
  163. /**
  164. * Replace placeholders with links.
  165. *
  166. * @param string $text The text to operate on.
  167. * @param array $htmlOptions The options for the generated links.
  168. * @return string The text with links inserted.
  169. */
  170. protected function _linkUrls($text, $htmlOptions)
  171. {
  172. $replace = [];
  173. foreach ($this->_placeholders as $hash => $content) {
  174. $link = $url = $content['content'];
  175. $envelope = $content['envelope'];
  176. if (!preg_match('#^[a-z]+\://#i', $url)) {
  177. $url = 'http://' . $url;
  178. }
  179. $replace[$hash] = $envelope[0] . $this->Html->link($link, $url, $htmlOptions) . $envelope[1];
  180. }
  181. return strtr($text, $replace);
  182. }
  183. /**
  184. * Links email addresses
  185. *
  186. * @param string $text The text to operate on
  187. * @param array $options An array of options to use for the HTML.
  188. * @return string
  189. * @see \Cake\View\Helper\TextHelper::autoLinkEmails()
  190. */
  191. protected function _linkEmails($text, $options)
  192. {
  193. $replace = [];
  194. foreach ($this->_placeholders as $hash => $content) {
  195. $url = $content['content'];
  196. $envelope = $content['envelope'];
  197. $replace[$hash] = $envelope[0] . $this->Html->link($url, 'mailto:' . $url, $options) . $envelope[1];
  198. }
  199. return strtr($text, $replace);
  200. }
  201. /**
  202. * Adds email links (<a href="mailto:....) to a given text.
  203. *
  204. * ### Options
  205. *
  206. * - `escape` Control HTML escaping of input. Defaults to true.
  207. *
  208. * @param string $text Text
  209. * @param array $options Array of HTML options, and options listed above.
  210. * @return string The text with links
  211. * @link http://book.cakephp.org/3.0/en/views/helpers/text.html#linking-email-addresses
  212. */
  213. public function autoLinkEmails($text, array $options = [])
  214. {
  215. $options += ['escape' => true];
  216. $this->_placeholders = [];
  217. $atom = '[\p{L}0-9!#$%&\'*+\/=?^_`{|}~-]';
  218. $text = preg_replace_callback(
  219. '/(?<=\s|^|\(|\>|\;)(' . $atom . '*(?:\.' . $atom . '+)*@[\p{L}0-9-]+(?:\.[\p{L}0-9-]+)+)/ui',
  220. [&$this, '_insertPlaceholder'],
  221. $text
  222. );
  223. if ($options['escape']) {
  224. $text = h($text);
  225. }
  226. return $this->_linkEmails($text, $options);
  227. }
  228. /**
  229. * Convert all links and email addresses to HTML links.
  230. *
  231. * ### Options
  232. *
  233. * - `escape` Control HTML escaping of input. Defaults to true.
  234. *
  235. * @param string $text Text
  236. * @param array $options Array of HTML options, and options listed above.
  237. * @return string The text with links
  238. * @link http://book.cakephp.org/3.0/en/views/helpers/text.html#linking-both-urls-and-email-addresses
  239. */
  240. public function autoLink($text, array $options = [])
  241. {
  242. $text = $this->autoLinkUrls($text, $options);
  243. return $this->autoLinkEmails($text, ['escape' => false] + $options);
  244. }
  245. /**
  246. * Highlights a given phrase in a text. You can specify any expression in highlighter that
  247. * may include the \1 expression to include the $phrase found.
  248. *
  249. * @param string $text Text to search the phrase in
  250. * @param string $phrase The phrase that will be searched
  251. * @param array $options An array of HTML attributes and options.
  252. * @return string The highlighted text
  253. * @see \Cake\Utility\Text::highlight()
  254. * @link http://book.cakephp.org/3.0/en/views/helpers/text.html#highlighting-substrings
  255. */
  256. public function highlight($text, $phrase, array $options = [])
  257. {
  258. return $this->_engine->highlight($text, $phrase, $options);
  259. }
  260. /**
  261. * Formats paragraphs around given text for all line breaks
  262. * <br /> added for single line return
  263. * <p> added for double line return
  264. *
  265. * @param string $text Text
  266. * @return string The text with proper <p> and <br /> tags
  267. * @link http://book.cakephp.org/3.0/en/views/helpers/text.html#converting-text-into-paragraphs
  268. */
  269. public function autoParagraph($text)
  270. {
  271. if (trim($text) !== '') {
  272. $text = preg_replace('|<br[^>]*>\s*<br[^>]*>|i', "\n\n", $text . "\n");
  273. $text = preg_replace("/\n\n+/", "\n\n", str_replace(["\r\n", "\r"], "\n", $text));
  274. $texts = preg_split('/\n\s*\n/', $text, -1, PREG_SPLIT_NO_EMPTY);
  275. $text = '';
  276. foreach ($texts as $txt) {
  277. $text .= '<p>' . nl2br(trim($txt, "\n")) . "</p>\n";
  278. }
  279. $text = preg_replace('|<p>\s*</p>|', '', $text);
  280. }
  281. return $text;
  282. }
  283. /**
  284. * Strips given text of all links (<a href=....)
  285. *
  286. * @param string $text Text
  287. * @return string The text without links
  288. * @see \Cake\Utility\Text::stripLinks()
  289. * @link http://book.cakephp.org/3.0/en/views/helpers/text.html#removing-links
  290. */
  291. public function stripLinks($text)
  292. {
  293. return $this->_engine->stripLinks($text);
  294. }
  295. /**
  296. * Truncates text.
  297. *
  298. * Cuts a string to the length of $length and replaces the last characters
  299. * with the ellipsis if the text is longer than length.
  300. *
  301. * ### Options:
  302. *
  303. * - `ellipsis` Will be used as Ending and appended to the trimmed string
  304. * - `exact` If false, $text will not be cut mid-word
  305. * - `html` If true, HTML tags would be handled correctly
  306. *
  307. * @param string $text String to truncate.
  308. * @param int $length Length of returned string, including ellipsis.
  309. * @param array $options An array of HTML attributes and options.
  310. * @return string Trimmed string.
  311. * @see \Cake\Utility\Text::truncate()
  312. * @link http://book.cakephp.org/3.0/en/views/helpers/text.html#truncating-text
  313. */
  314. public function truncate($text, $length = 100, array $options = [])
  315. {
  316. return $this->_engine->truncate($text, $length, $options);
  317. }
  318. /**
  319. * Truncates text starting from the end.
  320. *
  321. * Cuts a string to the length of $length and replaces the first characters
  322. * with the ellipsis if the text is longer than length.
  323. *
  324. * ### Options:
  325. *
  326. * - `ellipsis` Will be used as Beginning and prepended to the trimmed string
  327. * - `exact` If false, $text will not be cut mid-word
  328. *
  329. * @param string $text String to truncate.
  330. * @param int $length Length of returned string, including ellipsis.
  331. * @param array $options An array of HTML attributes and options.
  332. * @return string Trimmed string.
  333. * @see \Cake\Utility\Text::tail()
  334. * @link http://book.cakephp.org/3.0/en/views/helpers/text.html#truncating-the-tail-of-a-string
  335. */
  336. public function tail($text, $length = 100, array $options = [])
  337. {
  338. return $this->_engine->tail($text, $length, $options);
  339. }
  340. /**
  341. * Extracts an excerpt from the text surrounding the phrase with a number of characters on each side
  342. * determined by radius.
  343. *
  344. * @param string $text String to search the phrase in
  345. * @param string $phrase Phrase that will be searched for
  346. * @param int $radius The amount of characters that will be returned on each side of the founded phrase
  347. * @param string $ending Ending that will be appended
  348. * @return string Modified string
  349. * @see \Cake\Utility\Text::excerpt()
  350. * @link http://book.cakephp.org/3.0/en/views/helpers/text.html#extracting-an-excerpt
  351. */
  352. public function excerpt($text, $phrase, $radius = 100, $ending = '...')
  353. {
  354. return $this->_engine->excerpt($text, $phrase, $radius, $ending);
  355. }
  356. /**
  357. * Creates a comma separated list where the last two items are joined with 'and', forming natural language.
  358. *
  359. * @param array $list The list to be joined.
  360. * @param string|null $and The word used to join the last and second last items together with. Defaults to 'and'.
  361. * @param string $separator The separator used to join all the other items together. Defaults to ', '.
  362. * @return string The glued together string.
  363. * @see \Cake\Utility\Text::toList()
  364. * @link http://book.cakephp.org/3.0/en/views/helpers/text.html#converting-an-array-to-sentence-form
  365. */
  366. public function toList($list, $and = null, $separator = ', ')
  367. {
  368. return $this->_engine->toList($list, $and, $separator);
  369. }
  370. /**
  371. * Event listeners.
  372. *
  373. * @return array
  374. */
  375. public function implementedEvents()
  376. {
  377. return [];
  378. }
  379. }