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