-
Notifications
You must be signed in to change notification settings - Fork 2
/
NoFollow.php
532 lines (450 loc) · 10.3 KB
/
NoFollow.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
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
<?php
abstract class NoFollow
{
/**
* Operational status
*
* @var boolean
*/
protected $Active = false;
/**
* Parsing method used
*
* @var string
*/
protected $parseMethod;
/**
* Plugin Preferences
*
* @var array
*/
private $Prefs = [];
/**
* Exclude/ignore domains
*
* @var array
*/
private $excludeDomains = [];
/**
* Exclude/ignore pages
*
* @var array
*/
private $excludePages;
/**
* Admin chosen contexts
*
* @var array
*/
private $filterContext;
/**
* constructor
*/
public function __construct()
{
$this->init();
}
/**
* Initializes class
*
*/
protected function init()
{
$this->setPrefs()
->setStatus()
->setExcludePages()
->setExcludeDomains()
->setParseMethod();
}
/**
* Sets NoFollow::$Prefs - plugin preferences
*
*/
protected function setPrefs()
{
$this->Prefs = e107::getPlugPref('nofollow');
return $this;
}
/**
* Sets NoFollow::$Active - based on the plugin preference 'active'
*
*/
protected function setStatus()
{
$this->Active = $this->Prefs['active'];
return $this;
}
/**
* Sets NoFollow::$excludePages - based on the plugin
* - preference 'ignore_pages'
*
*/
protected function setExcludePages()
{
$this->excludePages =
$this->nlStringToArray($this->Prefs['ignore_pages']);
return $this;
}
/**
* Converts newline delimited string to numeric array
*
* @param string $inputString
* String that needs to be converted
* @return array
* Array created from string delimited with newlines
*/
protected function nlStringToArray($inputString)
{
$str = str_replace(["\r\n", "\n\r"], "|", $inputString);
return explode("|", $str);
}
/**
* Sets NoFollow::$excludeDomains
*
*/
protected function setExcludeDomains()
{
$this->excludeDomains = $this->solveExcludeDomains();
return $this;
}
/**
* Work out domain names that needs to be excluded
*
* @return array
* Array of all the domain names that needs to be excluded.
*/
protected function solveExcludeDomains()
{
if (isset($this->Prefs['ignore_domains'])) {
$domains = $this->nlStringToArray($this->Prefs['ignore_domains']);
// add current domain name too to the list
$domains[] = e_DOMAIN;
return array_unique($domains);
}
return [e_DOMAIN];
}
/**
* Sets NoFollow::$parseMethod - based on plugin
* - preference 'parse_method'
*
*/
protected function setParseMethod()
{
$this->parseMethod = trim($this->Prefs['parse_method']);
return $this;
}
/**
* Sets NoFollow::$filterContext - based on the plugin
* - preference 'filter_context'
*
*/
protected function setFilterContexts()
{
$this->filterContext = $this->Prefs['filter_context'];
}
/**
* Splits up $text by HTML tags and inner text scan for anchor tags and
* - apply 'nofollow' to 'suitable' anchor tag candidates (adopted from
* - linkwords plugin.)
*
* @param string $text
* Text to be parsed
* @return string
* Amended text
*/
protected function regexHtmlParse_Nofollow($text)
{
$nf_text = '';
$pattern = '#(<.*?>)#mis';
$fragments = preg_split($pattern, $text, -1,
PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);
foreach ($fragments as $fragment) {
if (
$this->isOpeningAnchor($fragment)
&& $this->needNoFollow($fragment)
) {
$nf_text .= $this->stampNoFollow($fragment);
} else {
$nf_text .= $fragment;
}
}
return $nf_text;
}
/**
* Tells if the text fragment is an opening anchor tag
*
* @param string $fragment
* String to be checked
* @return bool
* 'True' if it is 'false' if it isn't.
*/
protected function isOpeningAnchor($fragment)
{
return stripos($fragment, '<a') !== false && ! strpos($fragment, '<a');
}
/**
* Checks if anchor need NoFollow based on criteria such as has a
* - destination URL, destination URL has an excluded domain name
* - is a valid external URL
*
* @param string $anchor
* Anchor tag to be checked
* @return bool
* 'True' if it require nofollow 'false' if it doesn't.
*/
protected function needNoFollow($anchor)
{
$hrefValue = $this->getHrefValue($anchor);
if (null === $hrefValue || $this->isExcludeDomain($hrefValue)) {
return false;
}
if ($this->isValidExternalUrl($hrefValue)) {
return true;
}
return false;
}
/**
* Returns the href attribute value of an anchor tag
*
* @param string $anchor
* Anchor tag whose 'href' value/destination URL has to be extracted.
* @return string
* 'href' attribute value | null
*/
protected function getHrefValue($anchor)
{
$pattern =
'~<a (?>[^>h]++|\Bh|h(?!ref\b))*href\s*=\s*["\']?\K[^"\'>\s]++~i';
if (preg_match($pattern, $anchor, $match)) {
return $match[0];
}
return null;
}
/**
* Checks if given URL string is in the excluded domains list
*
* @param string $input
* String to be checked
* @return bool
* 'True' if it is an excluded domain 'false' if not.
*/
protected function isExcludeDomain($input)
{
foreach ($this->excludeDomains as $exclude) {
if (stripos($input, $exclude) !== false) {
return true;
}
}
return false;
}
/**
* Checks if given string is a valid URL
*
* @param string $input
*
* @return bool
* 'True' if it is a valid destination URL
* @fixme: original pattern was missing subdomains if it had only 2 chars
* - new one seems to circumvent that but need thorough testing
*/
protected function isValidExternalUrl($input)
{
$pattern = '(https?:\/\/(?:www\.|(?!www))[a-zA-Z0-9][a-zA-Z0-9-]+'
. '[a-zA-Z0-9]\.[^\s]{2,}|www\.[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]\.'
. '[^\s]{2,}|https?:\/\/(?:www\.|(?!www))[a-zA-Z0-9]\.'
. '[^\s]{2,}|www\.[a-zA-Z0-9]\.[^\s]{2,})';
$pattern2 = '/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/';
if (preg_match($pattern2, trim($input))) {
return true;
}
return false;
}
/**
* Adds rel="nofollow" attribute to HTML anchor elements if not present,
* - appends 'nofollow' to the value of rel attrubute if its present but
* - no nofollow value in it and return the string unaltered if already
* - has nofollow.
*
* @param string $anchor
* Opening anchor tag string
*
* @return string
* Nofollow parsed opening anchor tag
*/
protected function stampNoFollow($anchor)
{
if (strpos($anchor, 'nofollow')) {
return $anchor;
}
if (strpos($anchor, 'rel=')) {
//$pattern = "/rel=([\"'])([^\1]+?)\1/";
$pattern2 = '/rel=([\'"])(.*?)\1/';
//$replace = 'rel=\1nofollow \2\1 target="_blank"';
$replace2 = 'rel=\1\2 nofollow noopener noreferrer\1 target="_blank"';
return preg_replace($pattern2, $replace2, $anchor);
}
$pattern = '/<a /';
$replace = '<a rel="nofollow noopener noreferrer" target="_blank"';
return preg_replace($pattern, $replace, $anchor);
}
/**
* Does Nofollow parsing using simple_html_dom.php library
*
* @param string $text
* The text to be parsed
*
* @return string $text
* Nofollow parsed text
*/
protected function simpleHtmlDomParse_Nofollow($text)
{
$this->loadSimpleHtmlDomParserClass();
$dom = new simple_html_dom;
$dom->load($text);
$anchors = $dom->find('a');
foreach ($anchors as $anchor) {
if (
(string)$anchor->rel === 'nofollow'
|| $this->isAdminArea()
|| $this->isExcludePage()
|| ! $this->needNoFollow($anchor)
) {
continue;
}
if ((strpos((string)$anchor->rel,
'nofollow') === false) && strpos((string)$anchor->rel,
'external') !== false
) {
$anchor->rel = 'nofollow external noopener noreferrer';
$anchor->target = '_blank';
} else {
$anchor->rel = 'nofollow noopener noreferrer';
$anchor->target = '_blank';
}
}
$text = $dom->save();
$dom->clear();
return $text;
}
/**
* Load 'simple dom parser class' based on admin pref
* - global or local scope
*/
protected function loadSimpleHtmlDomParserClass()
{
if ($this->Prefs['use_global_path']) {
e107::library('load', 'simple_html_dom');
} else {
require_once __DIR__ . '/lib/simple_html_dom.php';
}
}
/**
* Checks if admin area
*
* @return bool
*/
protected function isAdminArea()
{
return e_ADMIN_AREA;
}
/**
* Checks if currently parsing page matches an exclude page
*
* @return boolean
* 'True' if yes 'false' if no
*/
protected function isExcludePage()
{
$current_page = e_REQUEST_URI; //$_SERVER['REQUEST_URI']
if (count($this->excludePages) > 0) {
foreach ($this->excludePages as $xpage) {
if (strpos($current_page, $xpage) !== false) {
return true;
}
}
}
return false;
}
/**
* Checks if the currently parsing $text is in NoFollow plugin's
* - parse filter context
*
* @param $context
*
* @return bool
*/
protected function isInContext($context)
{
$contextList = $this->getContextList();
if (null === $contextList) {
return true;
}
foreach ($contextList as $contextItem) {
if ($contextItem === $context) {
return true;
}
}
return false;
}
/**
* Gets the content context preference translated to e107 specification
*
* @return array|null
* Content context array or null
*/
protected function getContextList()
{
$contextPref = $this->filterContext;
switch ($contextPref) {
case 1:
return ['USER_TITLE', 'USER_BODY'];
break;
case 2:
return ['TITLE', 'BODY', 'USER_TITLE', 'USER_BODY'];
break;
case 3:
default:
return null;
}
}
/**
* Checks if the anchor tag's destination URL (href value)
* - is an excluded domain
*
* @param string $anchor
* The hyperlink anchor tag to be checked
*
* @return boolean
* 'True' if it is an excluded domain 'false' otherwise.
*/
protected function hasExcludeDomain($anchor)
{
$excludes = $this->excludeDomains;
$href = $this->getHrefValue($anchor);
if (null !== $href && $this->isValidExternalUrl($href)) {
foreach ($excludes as $exclude) {
if (strpos($href, $exclude) !== false) {
return true;
}
}
}
return false;
}
/**
* Debug logger
*
* @param string $content
* Content to log
* @param string|array $logname
* Optional log name
*/
private static function d($content, $logname = 'Nofollow-Debug')
{
$path = e_PLUGIN . 'nofollow/' . $logname . '.txt';
if (is_array($content)) {
$content = var_export($content, true);
}
file_put_contents($path, $content . "\n", FILE_APPEND);
unset($path, $content);
}
}