1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace SilverStripe\ExternalLinks\Tasks; |
4
|
|
|
|
5
|
|
|
use Psr\SimpleCache\CacheInterface; |
6
|
|
|
use SilverStripe\Core\Config\Configurable; |
7
|
|
|
use SilverStripe\Core\Injector\Injector; |
8
|
|
|
|
9
|
|
|
/** |
10
|
|
|
* Check links using curl |
11
|
|
|
*/ |
12
|
|
|
class CurlLinkChecker implements LinkChecker |
13
|
|
|
{ |
14
|
|
|
use Configurable; |
15
|
|
|
|
16
|
|
|
/** |
17
|
|
|
* If we want to follow redirects a 301 http code for example |
18
|
|
|
* Set via YAML file |
19
|
|
|
* |
20
|
|
|
* @config |
21
|
|
|
* @var boolean |
22
|
|
|
*/ |
23
|
|
|
private static $follow_location = false; |
|
|
|
|
24
|
|
|
|
25
|
|
|
/** |
26
|
|
|
* If we want to bypass the cache |
27
|
|
|
* Set via YAML file |
28
|
|
|
* |
29
|
|
|
* @config |
30
|
|
|
* @var boolean |
31
|
|
|
*/ |
32
|
|
|
private static $bypass_cache = false; |
|
|
|
|
33
|
|
|
|
34
|
|
|
/** |
35
|
|
|
* Return cache |
36
|
|
|
* |
37
|
|
|
* @return CacheInterface |
38
|
|
|
*/ |
39
|
|
|
protected function getCache() |
40
|
|
|
{ |
41
|
|
|
return Injector::inst()->get(CacheInterface::class . '.CurlLinkChecker'); |
42
|
|
|
} |
43
|
|
|
|
44
|
|
|
/** |
45
|
|
|
* Determine the http status code for a given link |
46
|
|
|
* |
47
|
|
|
* @param string $href URL to check |
48
|
|
|
* @return int HTTP status code, or null if not checkable (not a link) |
49
|
|
|
*/ |
50
|
|
|
public function checkLink($href) |
51
|
|
|
{ |
52
|
|
|
// Skip non-external links |
53
|
|
|
if (!preg_match('/^https?[^:]*:\/\//', $href)) { |
54
|
|
|
return null; |
55
|
|
|
} |
56
|
|
|
|
57
|
|
|
$cacheKey = md5($href); |
58
|
|
|
if (!$this->config()->get('bypass_cache')) { |
59
|
|
|
// Check if we have a cached result |
60
|
|
|
$result = $this->getCache()->get($cacheKey, false); |
61
|
|
|
if ($result !== false) { |
62
|
|
|
return $result; |
63
|
|
|
} |
64
|
|
|
} |
65
|
|
|
|
66
|
|
|
// No cached result so just request |
67
|
|
|
$handle = curl_init($href); |
68
|
|
|
curl_setopt($handle, CURLOPT_RETURNTRANSFER, true); |
|
|
|
|
69
|
|
|
if ($this->config()->get('follow_location')) { |
70
|
|
|
curl_setopt($handle, CURLOPT_FOLLOWLOCATION, true); |
71
|
|
|
} |
72
|
|
|
curl_setopt($handle, CURLOPT_CONNECTTIMEOUT, 5); |
73
|
|
|
curl_setopt($handle, CURLOPT_TIMEOUT, 10); |
74
|
|
|
curl_exec($handle); |
|
|
|
|
75
|
|
|
$httpCode = curl_getinfo($handle, CURLINFO_HTTP_CODE); |
|
|
|
|
76
|
|
|
curl_close($handle); |
|
|
|
|
77
|
|
|
|
78
|
|
|
if (!$this->config()->get('bypass_cache')) { |
79
|
|
|
// Cache result |
80
|
|
|
$this->getCache()->set($cacheKey, $httpCode); |
81
|
|
|
} |
82
|
|
|
return $httpCode; |
83
|
|
|
} |
84
|
|
|
} |
85
|
|
|
|