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