4 * Description: Blocking bots based on detecting bots/crawlers/spiders via the user agent and http_from header.
6 * Author: Philipp Holzer <admin@philipp.info>
11 use Friendica\Core\Config;
12 use Friendica\Core\Hook;
13 use Friendica\Core\System;
14 use Jaybizzle\CrawlerDetect\CrawlerDetect;
15 use Friendica\Core\Logger;
17 require_once __DIR__ . DIRECTORY_SEPARATOR . 'vendor' . DIRECTORY_SEPARATOR . 'autoload.php';
19 function blockbot_install() {
20 Hook::register('init_1', __FILE__, 'blockbot_init_1');
24 function blockbot_uninstall() {
25 Hook::unregister('init_1', __FILE__, 'blockbot_init_1');
28 function blockbot_init_1(App $a) {
29 if (empty($_SERVER['HTTP_USER_AGENT'])) {
33 $logdata = ['agent' => $_SERVER['HTTP_USER_AGENT'], 'uri' => $_SERVER['REQUEST_URI']];
35 // List of known crawlers. They are added here to avoid having them logged at the end of the function.
36 // This helps to detect false positives.
37 $agents = ['SEMrushBot', 's~feedly-nikon3', 'Qwantify/Bleriot/', 'ltx71', 'Sogou web spider/',
38 'Diffbot/', 'Twitterbot/', 'YisouSpider/', 'evc-batch/', 'LivelapBot/', 'TrendsmapResolver/',
39 'PaperLiBot/', 'Nuzzel', 'um-LN/', 'Google Favicon', 'Datanyze', 'BLEXBot/', '360Spider',
40 'adscanner/', 'HeadlessChrome', 'wpif', 'startmebot/', 'Googlebot/', 'Applebot/',
41 'facebookexternalhit/', 'GoogleImageProxy', 'bingbot/', 'heritrix/', 'ldspider',
42 'AwarioRssBot/', 'Zabbix'];
44 foreach ($agents as $agent) {
45 if (stristr($_SERVER['HTTP_USER_AGENT'], $agent)) {
46 System::httpExit(403, 'Bots are not allowed');
50 // This switch here is just meant for developers who want to add more bots to the list above
51 if (!Config::get('blockbot', 'training')) {
55 $crawlerDetect = new CrawlerDetect();
57 if (!$crawlerDetect->isCrawler()) {
58 logger::debug('Good user agent detected', $logdata);
62 // List of false positives' strings of known "good" agents.
63 $agents = ['fediverse.network crawler', 'Active_Pods_CheckBot_3.0', 'Social-Relay/',
64 'curl', 'zgrab', 'Go-http-client', 'curb', 'github.com', 'reqwest', 'Feedly/',
65 'Python-urllib/', 'Liferea/', 'aiohttp/', 'WordPress.com Reader', 'hackney/',
66 'Faraday v', 'okhttp', 'UniversalFeedParser', 'PixelFedBot', 'python-requests',
67 'WordPress/', 'http.rb/', 'Apache-HttpClient/', 'WordPress.com;'];
69 foreach ($agents as $agent) {
70 if (stristr($_SERVER['HTTP_USER_AGENT'], $agent)) {
71 logger::notice('False positive', $logdata);
76 logger::info('Blocked bot', $logdata);
77 System::httpExit(403, 'Bots are not allowed');