/mvc/helpers/text
[return to app]1
<?php
2 /**
3 * Text Helper
4 *
5 * This is CakePHP 2.0 TextHelper class updated to PHP5 syntax for Vork
6 *
7 * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
8 * Copyright 2005-2010, Cake Software Foundation, Inc. (http://cakefoundation.org)
9 *
10 * Licensed under The MIT License
11 * Redistributions of files must retain the above copyright notice.
12 *
13 * @copyright Copyright 2005-2010, Cake Software Foundation, Inc. (http://cakefoundation.org)
14 * @link http://cakephp.org CakePHP(tm) Project
15 * @package cake.libs.view.helpers
16 * @since CakePHP(tm) v 0.10.0.1076
17 * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
18 */
19
20 /**
21 * Text helper library.
22 *
23 * Text manipulations: Highlight, excerpt, truncate, strip of links, convert email addresses to mailto: links...
24 *
25 * @package cake.libs.view.helpers
26 * @link http://book.cakephp.org/view/1469/Text
27 */
28
29 class textHelper{
30
31 /**
32 * Highlights a given phrase in a text. You can specify any expression in highlighter that
33 * may include the \1 expression to include the $phrase found.
34 *
35 * ### Options:
36 *
37 * - `format` The piece of html with that the phrase will be highlighted
38 * - `html` If true, will ignore any HTML tags, ensuring that only the correct text is highlighted
39 *
40 * @param string $text Text to search the phrase in
41 * @param string $phrase The phrase that will be searched
42 * @param array $options An array of html attributes and options.
43 * @return string The highlighted text
44 * @access public
45 * @link http://book.cakephp.org/view/1469/Text#highlight-1622
46 */
47 public function highlight($text, $phrase, $options = array()) {
48 if (empty($phrase)) {
49 return $text;
50 }
51
52 $default = array(
53 'format' => '<span class="highlight">\1</span>',
54 'html' => false
55 );
56 $options = array_merge($default, $options);
57 extract($options);
58
59 if (is_array($phrase)) {
60 $replace = array();
61 $with = array();
62 foreach ($phrase as $key => $segment) {
63 $segment = "($segment)";
64 if ($html) {
65 $segment = "(?![^<]+>)$segment(?![^<]+>)";
66 }
67
68 $with[] = (is_array($format)) ? $format[$key] : $format;
69 $replace[] = "|$segment|iu";
70 }
71
72 return preg_replace($replace, $with, $text);
73 } else {
74 $phrase = "($phrase)";
75 if ($html) {
76 $phrase = "(?![^<]+>)$phrase(?![^<]+>)";
77 }
78
79 return preg_replace("|$phrase|iu", $format, $text);
80 }
81 }
82
83 /**
84 * Strips given text of all links (<a href=....)
85 *
86 * @param string $text Text
87 * @return string The text without links
88 * @access public
89 * @link http://book.cakephp.org/view/1469/Text#stripLinks-1623
90 */
91 public function stripLinks($text) {
92 return preg_replace('|<a\s+[^>]+>|im', '', preg_replace('|<\/a>|im', '', $text));
93 }
94
95 /**
96 * Adds links (<a href=....) to a given text, by finding text that begins with
97 * strings like http:// and ftp://.
98 *
99 * @param string $text Text to add links to
100 * @param array $options Array of HTML options.
101 * @return string The text with links
102 * @access public
103 * @link http://book.cakephp.org/view/1469/Text#autoLinkUrls-1619
104 */
105 public function autoLinkUrls($text, $htmlOptions = array()) {
106 $this->_linkOptions = $htmlOptions;
107 $text = preg_replace_callback(
108 '#(?<!href="|">)((?:https?|ftp|nntp)://[^\s<>()]+)#i',
109 array(&$this, '_linkBareUrl'),
110 $text
111 );
112 return preg_replace_callback(
113 '#(?<!href="|">)(?<!http://|https://|ftp://|nntp://)(www\.[^\n\%\ <]+[^<\n\%\,\.\ <])(?<!\))#i',
114 array(&$this, '_linkUrls'),
115 $text
116 );
117 }
118
119 /**
120 * Links urls that include http://
121 *
122 * @param array $matches
123 * @return string
124 * @see TextHelper::autoLinkUrls()
125 */
126 private function _linkBareUrl($matches) {
127 $html = get::helper('html');
128 return $html->link($matches[0], $matches[0], $this->_linkOptions);
129 }
130
131 /**
132 * Links urls missing http://
133 *
134 * @param array $matches
135 * @return string
136 * @see TextHelper::autoLinkUrls()
137 */
138 private function _linkUrls($matches) {
139 $html = get::helper('html');
140 return $html->link('http://' . $matches[0], $matches[0], $this->_linkOptions);
141 }
142
143 /**
144 * Links email addresses
145 *
146 * @param array $matches
147 * @return string
148 * @see TextHelper::autoLinkUrls()
149 */
150 private function _linkEmails($matches) {
151 $html = get::helper('html');
152 return $html->link( 'mailto:' . $matches[0], $matches[0],$this->_linkOptions);
153 }
154
155 /**
156 * Adds email links (<a href="mailto:....) to a given text.
157 *
158 * @param string $text Text
159 * @param array $options Array of HTML options.
160 * @return string The text with links
161 * @access public
162 * @link http://book.cakephp.org/view/1469/Text#autoLinkEmails-1618
163 */
164 public function autoLinkEmails($text, $options = array()) {
165 $this->_linkOptions = $options;
166 $atom = '[a-z0-9!#$%&\'*+\/=?^_`{|}~-]';
167 return preg_replace_callback(
168 '/(' . $atom . '+(?:\.' . $atom . '+)*@[a-z0-9-]+(?:\.[a-z0-9-]+)+)/i',
169 array(&$this, '_linkEmails'),
170 $text
171 );
172 }
173
174 /**
175 * Convert all links and email adresses to HTML links.
176 *
177 * @param string $text Text
178 * @param array $options Array of HTML options.
179 * @return string The text with links
180 * @access public
181 * @link http://book.cakephp.org/view/1469/Text#autoLink-1620
182 */
183 public function autoLink($text, $options = array()) {
184 return $this->autoLinkEmails($this->autoLinkUrls($text, $options), $options);
185 }
186
187 /**
188 * Truncates text.
189 *
190 * Cuts a string to the length of $length and replaces the last characters
191 * with the ending if the text is longer than length.
192 *
193 * ### Options:
194 *
195 * - `ending` Will be used as Ending and appended to the trimmed string
196 * - `exact` If false, $text will not be cut mid-word
197 * - `html` If true, HTML tags would be handled correctly
198 *
199 * @param string $text String to truncate.
200 * @param integer $length Length of returned string, including ellipsis.
201 * @param array $options An array of html attributes and options.
202 * @return string Trimmed string.
203 * @access public
204 * @link http://book.cakephp.org/view/1469/Text#truncate-1625
205 */
206 public function truncate($text, $length = 100, $options = array()) {
207 $default = array(
208 'ending' => '...', 'exact' => true, 'html' => false
209 );
210 $options = array_merge($default, $options);
211 extract($options);
212
213 if ($html) {
214 if (mb_strlen(preg_replace('/<.*?>/', '', $text)) <= $length) {
215 return $text;
216 }
217 $totalLength = mb_strlen(strip_tags($ending));
218 $openTags = array();
219 $truncate = '';
220
221 preg_match_all('/(<\/?([\w+]+)[^>]*>)?([^<>]*)/', $text, $tags, PREG_SET_ORDER);
222 foreach ($tags as $tag) {
223 if (!preg_match('/img|br|input|hr|area|base|basefont|col|frame|isindex|link|meta|param/s',
$tag[2])) {
224 if (preg_match('/<[\w]+[^>]*>/s', $tag[0])) {
225 array_unshift($openTags, $tag[2]);
226 } else if (preg_match('/<\/([\w]+)[^>]*>/s', $tag[0], $closeTag)) {
227 $pos = array_search($closeTag[1], $openTags);
228 if ($pos !== false) {
229 array_splice($openTags, $pos, 1);
230 }
231 }
232 }
233 $truncate .= $tag[1];
234
235 $contentLength
236 = mb_strlen(preg_replace('/&[0-9a-z]{2,8};|&#[0-9]{1,7};|&#x[0-9a-f]{1,6};/i', ' ', $tag[3]));
237 if ($contentLength + $totalLength > $length) {
238 $left = $length - $totalLength;
239 $entitiesLength = 0;
240 if (preg_match_all('/&[0-9a-z]{2,8};|&#[0-9]{1,7};|&#x[0-9a-f]{1,6};/i',
241 $tag[3], $entities, PREG_OFFSET_CAPTURE)) {
242 foreach ($entities[0] as $entity) {
243 if ($entity[1] + 1 - $entitiesLength <= $left) {
244 $left--;
245 $entitiesLength += mb_strlen($entity[0]);
246 } else {
247 break;
248 }
249 }
250 }
251
252 $truncate .= mb_substr($tag[3], 0 , $left + $entitiesLength);
253 break;
254 } else {
255 $truncate .= $tag[3];
256 $totalLength += $contentLength;
257 }
258 if ($totalLength >= $length) {
259 break;
260 }
261
262 }
263 } else {
264 if (mb_strlen($text) <= $length) {
265 return $text;
266 } else {
267 $truncate = mb_substr($text, 0, $length - mb_strlen($ending));
268 }
269 }
270 if (!$exact) {
271 $spacepos = mb_strrpos($truncate, ' ');
272 if (isset($spacepos)) {
273 if ($html) {
274 $bits = mb_substr($truncate, $spacepos);
275 preg_match_all('/<\/([a-z]+)>/', $bits, $droppedTags, PREG_SET_ORDER);
276 if (!empty($droppedTags)) {
277 foreach ($droppedTags as $closingTag) {
278 if (!in_array($closingTag[1], $openTags)) {
279 array_unshift($openTags, $closingTag[1]);
280 }
281 }
282 }
283 }
284 $truncate = mb_substr($truncate, 0, $spacepos);
285 }
286 }
287 $truncate .= $ending;
288
289 if ($html) {
290 foreach ($openTags as $tag) {
291 $truncate .= '</'.$tag.'>';
292 }
293 }
294
295 return $truncate;
296 }
297
298 /**
299 * Extracts an excerpt from the text surrounding the phrase with a number of characters on each side
300 * determined by radius.
301 *
302 * @param string $text String to search the phrase in
303 * @param string $phrase Phrase that will be searched for
304 * @param integer $radius The amount of characters that will be returned on each side of the founded phrase
305 * @param string $ending Ending that will be appended
306 * @return string Modified string
307 * @access public
308 * @link http://book.cakephp.org/view/1469/Text#excerpt-1621
309 */
310 public function excerpt($text, $phrase, $radius = 100, $ending = '...') {
311 if (empty($text) or empty($phrase)) {
312 return $this->truncate($text, $radius * 2, array('ending' => $ending));
313 }
314
315 $phraseLen = mb_strlen($phrase);
316 if ($radius < $phraseLen) {
317 $radius = $phraseLen;
318 }
319
320 $pos = mb_strpos(mb_strtolower($text), mb_strtolower($phrase));
321
322 $startPos = 0;
323 if ($pos > $radius) {
324 $startPos = $pos - $radius;
325 }
326
327 $textLen = mb_strlen($text);
328
329 $endPos = $pos + $phraseLen + $radius;
330 if ($endPos >= $textLen) {
331 $endPos = $textLen;
332 }
333
334 $excerpt = mb_substr($text, $startPos, $endPos - $startPos);
335 if ($startPos != 0) {
336 $excerpt = substr_replace($excerpt, $ending, 0, $phraseLen);
337 }
338
339 if ($endPos != $textLen) {
340 $excerpt = substr_replace($excerpt, $ending, -$phraseLen);
341 }
342
343 return $excerpt;
344 }
345
346 /**
347 * Creates a comma separated list where the last two items are joined with 'and', forming natural English
348 *
349 * @param array $list The list to be joined
350 * @param string $and The word used to join the last and second last items together with. Defaults to 'and'
351 * @param string $separator The separator used to join all othe other items together. Defaults to ', '
352 * @return string The glued together string.
353 * @access public
354 * @link http://book.cakephp.org/view/1469/Text#toList-1624
355 */
356 public function toList($list, $and = 'and', $separator = ', ') {
357 if (count($list) > 1) {
358 return implode($separator, array_slice($list, null, -1)) . ' ' . $and . ' ' . array_pop($list);
359 } else {
360 return array_pop($list);
361 }
362 }
363 }
364