-
Notifications
You must be signed in to change notification settings - Fork 0
/
PageScannerService.php
232 lines (193 loc) · 6.66 KB
/
PageScannerService.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
<?php
namespace Pushword\PageScanner;
use Doctrine\ORM\EntityManagerInterface;
use PiedWeb\UrlHarvester\Harvest;
use Pushword\Core\Component\App\AppPool;
use Pushword\Core\Component\Router\RouterInterface as PwRouter;
use Pushword\Core\Entity\PageInterface;
use Pushword\Core\Utils\GenerateLivePathForTrait;
use Pushword\Core\Utils\KernelTrait;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\KernelInterface;
use Twig\Environment as Twig;
/**
* Permit to find error in image or link.
*/
class PageScannerService
{
use GenerateLivePathForTrait;
use KernelTrait;
/** @var \Pushword\Core\Component\App\AppConfig */
protected $app;
/** @var EntityManagerInterface */
protected $em;
protected $pageHtml;
/** @var Twig */
protected $twig;
protected $currentPage;
protected $webDir;
protected $previousRequest;
/** @var AppPool */
protected $apps;
protected $linksCheckedCounter = 0;
protected $errors = [];
protected $everChecked = [];
public static $appKernel;
public function __construct(
Twig $twig,
EntityManagerInterface $em,
string $webDir,
AppPool $apps,
PwRouter $router,
KernelInterface $kernel
) {
$this->twig = $twig;
$this->router = $router;
$this->router->setUseCustomHostPath(false);
$this->em = $em;
$this->webDir = $webDir;
$this->apps = $apps;
static::loadKernel($kernel);
}
protected function resetErrors()
{
$this->errors = [];
}
public function scan(PageInterface $page)
{
$this->app = $this->apps->get($page->getHost());
$this->currentPage = $page;
$this->resetErrors();
$this->pageHtml = '';
if (false !== $page->getRedirection()) {
// check $page->getRedirection() return 20X
return true; // or status code
}
$liveUri = $this->generateLivePathFor($page);
$this->pageHtml = $this->getHtml($liveUri);
// 2. Je récupère tout les liens et je les check
// href="", data-rot="" data-img="", src="", data-bg
if ($this->pageHtml) {
$this->checkLinkedDocs($this->getLinkedDocs());
}
return empty($this->errors) ? true : $this->errors;
}
protected function getHtml($liveUri)
{
$request = Request::create($liveUri);
$response = static::$appKernel->handle($request);
if ($response->isRedirect()) {
//. $linkedDocs[] = $response->headers->get('location');
// todo check redirection
return;
} elseif (200 != $response->getStatusCode()) {
$this->addError('error on generating the page ('.$response->getStatusCode().')');
return;
}
return $response->getContent();
}
protected function addError($message)
{
$this->errors[] = [
'message' => $message,
'page' => [
'id' => $this->currentPage->getId(),
'slug' => $this->currentPage->getSlug(),
'h1' => $this->currentPage->getH1(),
'metaRobots' => $this->currentPage->getMetaRobots(),
'host' => $this->currentPage->getHost(),
],
];
}
protected static function prepareForRegex($var)
{
if (\is_string($var)) {
return preg_quote($var, '/');
}
$var = array_map('static::prepareForRegex', $var);
return '('.implode('|', $var).')';
}
protected static function isWebLink(string $url)
{
return preg_match('@^((?:(http:|https:)//([\w\d-]+\.)+[\w\d-]+){0,1}(/?[\w~,;\-\./?%&+#=]*))$@', $url);
}
protected function getLinkedDocs(): array
{
$urlInAttributes = ' '.self::prepareForRegex(['href', 'data-rot', 'src', 'data-img', 'data-bg']);
$regex = '/'.$urlInAttributes.'=((["\'])([^\3]+)\3|([^\s>]+)[\s>])/iU';
preg_match_all($regex, $this->pageHtml, $matches);
$linkedDocs = [];
$matchesCount = \count($matches[0]);
for ($k = 0; $k < $matchesCount; ++$k) {
$uri = isset($matches[4][$k]) ? $matches[4][$k] : $matches[5][$k];
$uri = 'data-rot' == $matches[1][$k] ? str_rot13($uri) : $uri;
$uri = strtok($uri, '#');
$uri = $this->removeBase($uri);
if ('' !== $uri && self::isWebLink($uri)) {
$linkedDocs[] = $uri;
}
}
return array_unique($linkedDocs);
}
protected function removeBase($url)
{
if (0 === strpos($url, 'https://'.$this->app->getMainHost())) {
return substr($url, \strlen('https://'.$this->app->getMainHost()));
}
return $url;
}
public function getLinksCheckedCounter()
{
return $this->linksCheckedCounter;
}
protected function checkLinkedDocs(array $linkedDocs)
{
foreach ($linkedDocs as $uri) {
++$this->linksCheckedCounter;
if (! \is_string($uri)) {
continue;
}
if (('/' == $uri[0] && ! $this->uriExist($uri))
|| (0 === strpos($uri, 'http') && ! $this->urlExist($uri))) {
$this->addError('<code>'.$uri.'</code> introuvable');
}
}
}
/**
* this is really slow on big website.
*
* @param string $uri
*
* @return bool
*/
protected function urlExist($uri)
{
$harvest = Harvest::fromUrl(
$uri,
'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.107 Safari/537.36',
'en,en-US;q=0.5',
$this->previousRequest
);
if (\is_int($harvest) || 200 !== $harvest->getResponse()->getStatusCode()) {
return false;
}
$this->previousRequest = $harvest->getResponse()->getRequest();
return true;
}
protected function uriExist($uri)
{
$slug = ltrim($uri, '/');
if (isset($this->everChecked[$slug])) {
return $this->everChecked[$slug];
}
$checkDatabase = 0 !== strpos($slug, 'media/'); // we avoid to check in db the media, file exists is enough
$page = true !== $checkDatabase ? null : $this->em->getRepository(\get_class($this->currentPage))
->findOneBy(['slug' => '' == $slug ? 'homepage' : $slug]); // todo add domain check (currentPage domain)
$this->everChecked[$slug] = (
null === $page
&& ! file_exists($this->webDir.'/'.$slug)
&& 'feed.xml' !== $slug
) ? false : true;
return $this->everChecked[$slug];
}
}