-
Notifications
You must be signed in to change notification settings - Fork 3.4k
/
TextHelper.php
275 lines (252 loc) · 9.22 KB
/
TextHelper.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
<?php
declare(strict_types=1);
/**
* CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
* Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
* @link https://cakephp.org CakePHP(tm) Project
* @since 0.10.0
* @license https://opensource.org/licenses/mit-license.php MIT License
*/
namespace Cake\View\Helper;
use Cake\Utility\Security;
use Cake\Utility\Text;
use Cake\View\Helper;
use function Cake\Core\h;
/**
* Text helper library.
*
* Text manipulations: Highlight, excerpt, truncate, strip of links, convert email addresses to mailto: links...
*
* @property \Cake\View\Helper\HtmlHelper $Html
* @method string excerpt(string $text, string $phrase, int $radius = 100, string $ending = '...') See Text::excerpt()
* @method string highlight(string $text, array|string $phrase, array $options = []) See Text::highlight()
* @method string slug(string $string, array|string $options = []) See Text::slug()
* @method string tail(string $text, int $length = 100, array $options = []) See Text::tail()
* @method string toList(array $list, ?string $and = null, string $separator = ', ') See Text::toList()
* @method string truncate(string $text, int $length = 100, array $options = []) See Text::truncate()
* @link https://book.cakephp.org/5/en/views/helpers/text.html
* @see \Cake\Utility\Text
*/
class TextHelper extends Helper
{
/**
* helpers
*
* @var array
*/
protected array $helpers = ['Html'];
/**
* An array of hashes and their contents.
* Used when inserting links into text.
*
* @var array<string, array>
*/
protected array $_placeholders = [];
/**
* Call methods from String utility class
*
* @param string $method Method to invoke
* @param array $params Array of params for the method.
* @return mixed Whatever is returned by called method, or false on failure
*/
public function __call(string $method, array $params): mixed
{
return Text::{$method}(...$params);
}
/**
* Adds links (<a href=....) to a given text, by finding text that begins with
* strings like http:// and ftp://.
*
* ### Options
*
* - `escape` Control HTML escaping of input. Defaults to true.
*
* @param string $text Text
* @param array<string, mixed> $options Array of HTML options, and options listed above.
* @return string The text with links
* @link https://book.cakephp.org/5/en/views/helpers/text.html#linking-urls
*/
public function autoLinkUrls(string $text, array $options = []): string
{
$this->_placeholders = [];
$options += ['escape' => true];
// phpcs:disable Generic.Files.LineLength
$pattern = '/(?:(?<!href="|src="|">)
(?>
(
(?<left>[\[<(]) # left paren,brace
(?>
# Lax match URL
(?<url>(?:https?|ftp|nntp):\/\/[\p{L}0-9.\-_:]+(?:[\/?][\p{L}0-9.\-_:\/?=&>\[\]\(\)\#\@\+~!;,%]+[^-_:?>\[\(\@\+~!;<,.%\s])?)
(?<right>[\])>]) # right paren,brace
)
)
|
(?<url_bare>(?P>url)) # A bare URL. Use subroutine
)
)/ixu';
// phpcs:enable Generic.Files.LineLength
$text = (string)preg_replace_callback(
$pattern,
[&$this, '_insertPlaceHolder'],
$text
);
// phpcs:disable Generic.Files.LineLength
$text = preg_replace_callback(
'#(?<!href="|">)(?<!\b[[:punct:]])(?<!http://|https://|ftp://|nntp://)www\.[^\s\n\%\ <]+[^\s<\n\%\,\.\ ](?<!\))#i',
[&$this, '_insertPlaceHolder'],
$text
);
// phpcs:enable Generic.Files.LineLength
if ($options['escape']) {
$text = h($text);
}
return $this->_linkUrls($text, $options);
}
/**
* Saves the placeholder for a string, for later use. This gets around double
* escaping content in URL's.
*
* @param array $matches An array of regexp matches.
* @return string Replaced values.
*/
protected function _insertPlaceHolder(array $matches): string
{
$match = $matches[0];
$envelope = ['', ''];
if (isset($matches['url'])) {
$match = $matches['url'];
$envelope = [$matches['left'], $matches['right']];
}
if (isset($matches['url_bare'])) {
$match = $matches['url_bare'];
}
$key = hash_hmac('sha1', $match, Security::getSalt());
$this->_placeholders[$key] = [
'content' => $match,
'envelope' => $envelope,
];
return $key;
}
/**
* Replace placeholders with links.
*
* @param string $text The text to operate on.
* @param array<string, mixed> $htmlOptions The options for the generated links.
* @return string The text with links inserted.
*/
protected function _linkUrls(string $text, array $htmlOptions): string
{
$replace = [];
foreach ($this->_placeholders as $hash => $content) {
$link = $url = $content['content'];
$envelope = $content['envelope'];
if (!preg_match('#^[a-z]+\://#i', $url)) {
$url = 'http://' . $url;
}
$replace[$hash] = $envelope[0] . $this->Html->link($link, $url, $htmlOptions) . $envelope[1];
}
return strtr($text, $replace);
}
/**
* Links email addresses
*
* @param string $text The text to operate on
* @param array<string, mixed> $options An array of options to use for the HTML.
* @return string
* @see \Cake\View\Helper\TextHelper::autoLinkEmails()
*/
protected function _linkEmails(string $text, array $options): string
{
$replace = [];
foreach ($this->_placeholders as $hash => $content) {
$url = $content['content'];
$envelope = $content['envelope'];
$replace[$hash] = $envelope[0] . $this->Html->link($url, 'mailto:' . $url, $options) . $envelope[1];
}
return strtr($text, $replace);
}
/**
* Adds email links (<a href="mailto:....") to a given text.
*
* ### Options
*
* - `escape` Control HTML escaping of input. Defaults to true.
*
* @param string $text Text
* @param array<string, mixed> $options Array of HTML options, and options listed above.
* @return string The text with links
* @link https://book.cakephp.org/5/en/views/helpers/text.html#linking-email-addresses
*/
public function autoLinkEmails(string $text, array $options = []): string
{
$options += ['escape' => true];
$this->_placeholders = [];
$atom = '[\p{L}0-9!#$%&\'*+\/=?^_`{|}~-]';
$text = preg_replace_callback(
'/(?<=\s|^|\(|\>|\;)(' . $atom . '*(?:\.' . $atom . '+)*@[\p{L}0-9-]+(?:\.[\p{L}0-9-]+)+)/ui',
[&$this, '_insertPlaceholder'],
$text
);
if ($options['escape']) {
$text = h($text);
}
return $this->_linkEmails($text, $options);
}
/**
* Convert all links and email addresses to HTML links.
*
* ### Options
*
* - `escape` Control HTML escaping of input. Defaults to true.
*
* @param string $text Text
* @param array<string, mixed> $options Array of HTML options, and options listed above.
* @return string The text with links
* @link https://book.cakephp.org/5/en/views/helpers/text.html#linking-both-urls-and-email-addresses
*/
public function autoLink(string $text, array $options = []): string
{
$text = $this->autoLinkUrls($text, $options);
return $this->autoLinkEmails($text, ['escape' => false] + $options);
}
/**
* Formats paragraphs around given text for all line breaks
* <br> added for single line return
* <p> added for double line return
*
* @param string|null $text Text
* @return string The text with proper <p> and <br> tags
* @link https://book.cakephp.org/5/en/views/helpers/text.html#converting-text-into-paragraphs
*/
public function autoParagraph(?string $text): string
{
$text ??= '';
if (trim($text) !== '') {
$text = (string)preg_replace('|<br[^>]*>\s*<br[^>]*>|i', "\n\n", $text . "\n");
$text = (string)preg_replace("/\n\n+/", "\n\n", str_replace(["\r\n", "\r"], "\n", $text));
$texts = preg_split('/\n\s*\n/', $text, -1, PREG_SPLIT_NO_EMPTY) ?: [];
$text = '';
foreach ($texts as $txt) {
$text .= '<p>' . nl2br(trim($txt, "\n")) . "</p>\n";
}
$text = (string)preg_replace('|<p>\s*</p>|', '', $text);
}
return $text;
}
/**
* Event listeners.
*
* @return array<string, mixed>
*/
public function implementedEvents(): array
{
return [];
}
}