|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Famdirksen\LaravelUTMUrls\Middleware; |
|
4
|
|
|
|
|
5
|
|
|
use Closure; |
|
6
|
|
|
|
|
7
|
|
|
class SetUTMUrls |
|
8
|
|
|
{ |
|
9
|
|
|
/** |
|
10
|
|
|
* Handle an incoming request. |
|
11
|
|
|
* |
|
12
|
|
|
* @param \Illuminate\Http\Request $request |
|
13
|
|
|
* @param \Closure $next |
|
14
|
|
|
* @return mixed |
|
15
|
|
|
*/ |
|
16
|
|
|
public function handle($request, Closure $next) |
|
17
|
|
|
{ |
|
18
|
|
|
$response = $next($request); |
|
19
|
|
|
|
|
20
|
|
|
if (config('utm-urls.enabled', false)) { |
|
21
|
|
|
if ($this->hasToAppend($request)) { |
|
22
|
|
|
$response->setContent($this->appendUtmsToString($response->getContent())); |
|
23
|
|
|
} |
|
24
|
|
|
} |
|
25
|
|
|
|
|
26
|
|
|
return $response; |
|
27
|
|
|
} |
|
28
|
|
|
|
|
29
|
|
|
/** |
|
30
|
|
|
* Check if we need to set the UTM attributes. |
|
31
|
|
|
* |
|
32
|
|
|
* @param \Illuminate\Http\Request $request |
|
33
|
|
|
* @return bool |
|
34
|
|
|
*/ |
|
35
|
|
|
public function hasToAppend($request) |
|
36
|
|
|
{ |
|
37
|
|
|
if (! $request->headers->has('x-do-not-append-campagne')) { |
|
38
|
|
|
return true; |
|
39
|
|
|
} |
|
40
|
|
|
|
|
41
|
|
|
return false; |
|
42
|
|
|
} |
|
43
|
|
|
|
|
44
|
|
|
/** |
|
45
|
|
|
* Append the UTM attributes to all urls. |
|
46
|
|
|
* |
|
47
|
|
|
* @param $string |
|
48
|
|
|
* @return null|string|string[] |
|
49
|
|
|
*/ |
|
50
|
|
|
protected function appendUtmsToString($string) |
|
51
|
|
|
{ |
|
52
|
|
|
$regex = '#(<a.*?href=")([^"]*)("[^>]*?>)#i'; |
|
53
|
|
|
|
|
54
|
|
|
return preg_replace_callback($regex, function ($match) { |
|
55
|
|
|
$url = $match[2]; |
|
56
|
|
|
|
|
57
|
|
|
//check if a href url is in skip link |
|
58
|
|
|
$aHrefLink = parse_url($url); |
|
59
|
|
|
|
|
60
|
|
|
if (isset($aHrefLink['host']) && ! empty($aHrefLink['host']) && in_array($aHrefLink['host'], config('utm-urls.skipped_hosts', []))) { |
|
61
|
|
|
return $match[0]; |
|
62
|
|
|
} else { |
|
63
|
|
|
//check if there is a # in the url |
|
64
|
|
|
if (strpos($url, '#') === false) { |
|
65
|
|
|
return $match[0]; |
|
66
|
|
|
} else { |
|
67
|
|
|
//check if there is already an ? in the url |
|
68
|
|
|
if (strpos($url, '?') === false) { |
|
69
|
|
|
$counter = 0; |
|
70
|
|
|
} else { |
|
71
|
|
|
$counter = 1; |
|
72
|
|
|
} |
|
73
|
|
|
|
|
74
|
|
|
//set all the utms |
|
75
|
|
|
foreach (config('utm-urls.utms', []) as $utm => $value) { |
|
76
|
|
|
if (! empty($value)) { |
|
77
|
|
|
if ($counter == 0) { |
|
78
|
|
|
$url .= '?'; |
|
79
|
|
|
} else { |
|
80
|
|
|
$url .= '&'; |
|
81
|
|
|
} |
|
82
|
|
|
|
|
83
|
|
|
$url .= 'utm_'.str_slug(strtolower($utm)).'='.$value; |
|
84
|
|
|
|
|
85
|
|
|
$counter++; |
|
86
|
|
|
} |
|
87
|
|
|
} |
|
88
|
|
|
|
|
89
|
|
|
return $match[1].$url.$match[3]; |
|
90
|
|
|
} |
|
91
|
|
|
} |
|
92
|
|
|
}, $string); |
|
93
|
|
|
} |
|
94
|
|
|
} |
|
95
|
|
|
|