123movies-seo/app/Http/Middleware/BlockAdLink.php

90 lines
2.4 KiB
PHP

<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
class BlockAdLink
{
protected $crawlerUserAgents = [
'Chrome-Lighthouse',
'google',
'Yahoo! Slurp',
'bingbot',
'yandex',
'baiduspider',
'facebookexternalhit',
'twitterbot',
'rogerbot',
'linkedinbot',
'embedly',
'quora link preview',
'showyoubot',
'outbrain',
'pinterest/0.',
'slackbot',
'vkShare',
'W3C_Validator',
'redditbot',
'Applebot',
'WhatsApp',
'flipboard',
'tumblr',
'bitlybot',
'SkypeUriPreview',
'nuzzel',
'Discordbot',
'Qwantify',
'pinterestbot',
'Bitrix link preview',
'XING-contenttabreceiver',
'developers.google.com/+/web/snippet',
];
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse) $next
* @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
*/
public function handle(Request $request, Closure $next, string $routeName = null)
{
if ($this->shouldBlock($request)) {
// abort(403, 'Unauthorized', ['X-Robots-Tag' => 'noindex, nofollow']);
return response('', 200)
->header('X-Robots-Tag', 'noindex, nofollow')
->header('Content-Type', 'application/javascript');
exit;
}
return $next($request);
}
protected function shouldBlock(Request $request): bool
{
$userAgent = strtolower($request->server->get('HTTP_USER_AGENT'));
$bufferAgent = $request->server->get('X-BUFFERBOT');
$shouldBlock = false;
if ( ! $userAgent) return false;
if ( ! $request->isMethod('GET')) return false;
// prerender if _escaped_fragment_ is in the query string
if ($request->query->has('_escaped_fragment_')) $shouldBlock = true;
// prerender if a crawler is detected
foreach ($this->crawlerUserAgents as $crawlerUserAgent) {
if (Str::contains($userAgent, strtolower($crawlerUserAgent))) {
$shouldBlock = true;
}
}
if ($bufferAgent) $shouldBlock = true;
return $shouldBlock;
}
}