Merge pull request #873 from annando/more-bots
[friendica-addons.git/.git] / blockbot / blockbot.php
1 <?php
2 /**
3  * Name: blockbot
4  * Description: Blocking bots based on detecting bots/crawlers/spiders via the user agent and http_from header.
5  * Version: 0.2
6  * Author: Philipp Holzer <admin@philipp.info>
7  * Author: Michael Vogel <https://pirati.ca/profile/heluecht>
8  *
9  */
10
11 use Friendica\App;
12 use Friendica\Core\Config;
13 use Friendica\Core\Hook;
14 use Friendica\Core\System;
15 use Jaybizzle\CrawlerDetect\CrawlerDetect;
16 use Friendica\Core\Logger;
17 use Friendica\Core\Renderer;
18 use Friendica\Core\L10n;
19
20 require_once __DIR__ . DIRECTORY_SEPARATOR . 'vendor' . DIRECTORY_SEPARATOR . 'autoload.php';
21
22 function blockbot_install() {
23         Hook::register('init_1', __FILE__, 'blockbot_init_1');
24 }
25
26
27 function blockbot_uninstall() {
28         Hook::unregister('init_1', __FILE__, 'blockbot_init_1');
29 }
30
31 function blockbot_addon_admin(&$a, &$o) {
32         $t = Renderer::getMarkupTemplate("admin.tpl", "addon/blockbot/");
33
34         $o = Renderer::replaceMacros($t, [
35                 '$submit' => L10n::t('Save Settings'),
36                 '$good_crawlers' => ['good_crawlers', L10n::t('Allow "good" crawlers'), Config::get('blockbot', 'good_crawlers'), "Don't block fediverse crawlers, relay servers and other bots with good purposes."],
37                 '$block_gab' => ['block_gab', L10n::t('Block GabSocial'), Config::get('blockbot', 'block_gab'), 'Block the software GabSocial. This will block every access for that software. You can block dedicated gab instances in the blocklist settings in the admin section.'],
38                 '$training' => ['training', L10n::t('Training mode'), Config::get('blockbot', 'training'), "Activates the training mode. This is only meant for developing purposes. Don't activate this on a production machine. This can cut communication with some systems."],
39         ]);
40 }
41
42 function blockbot_addon_admin_post(&$a) {
43         Config::set('blockbot', 'good_crawlers', $_POST['good_crawlers'] ?? false);
44         Config::set('blockbot', 'block_gab', $_POST['block_gab'] ?? false);
45         Config::set('blockbot', 'training', $_POST['training'] ?? false);
46         info(L10n::t('Settings updated.'). EOL);
47 }
48
49 function blockbot_init_1(App $a) {
50         if (empty($_SERVER['HTTP_USER_AGENT'])) {
51                 return;
52         }
53
54         $logdata = ['agent' => $_SERVER['HTTP_USER_AGENT'], 'uri' => $_SERVER['REQUEST_URI']];
55
56         // List of "good" crawlers
57         $good_agents = ['fediverse.space crawler', 'fediverse.network crawler', 'Active_Pods_CheckBot_3.0',
58                         'Social-Relay/', 'Test Certificate Info', 'Uptimebot/', 'GNUSocialBot'];
59
60         // List of known crawlers.
61         $agents = ['SemrushBot', 's~feedly-nikon3', 'Qwantify/Bleriot/', 'ltx71', 'Sogou web spider/',
62                 'Diffbot/', 'Twitterbot/', 'YisouSpider', 'evc-batch/', 'LivelapBot/', 'TrendsmapResolver/',
63                 'PaperLiBot/', 'Nuzzel', 'um-LN/', 'Google Favicon', 'Datanyze', 'BLEXBot/', '360Spider',
64                 'adscanner/', 'HeadlessChrome', 'wpif', 'startmebot/', 'Googlebot/', 'Applebot/',
65                 'facebookexternalhit/', 'GoogleImageProxy', 'bingbot/', 'heritrix/', 'ldspider',
66                 'AwarioRssBot/', 'Zabbix', 'TweetmemeBot/', 'dcrawl/', 'PhantomJS/', 'Googlebot-Image/',
67                 'CrowdTanglebot/', 'Mediapartners-Google', 'Baiduspider/', 'datagnionbot',
68                 'MegaIndex.ru/', 'SMUrlExpander', 'Hatena-Favicon/', 'Wappalyzer', 'FlipboardProxy/',
69                 'NetcraftSurveyAgent/', 'Dataprovider.com', 'SMTBot/', 'Nimbostratus-Bot/',
70                 'DuckDuckGo-Favicons-Bot/', 'IndieWebCards/', 'proximic', 'netEstate NE Crawler',
71                 'AhrefsBot/', 'YandexBot/', 'Exabot/', 'Mediumbot-MetaTagFetcher/', 'WhatsApp/',
72                 'TelegramBot', 'SurdotlyBot/', 'BingPreview/', 'SabsimBot/', 'CCBot/', 'WbSrch/',
73                 'DuckDuckBot-Https/', 'HTTP Banner Detection', 'YandexImages/', 'archive.org_bot',
74                 'ArchiveTeam ArchiveBot/', 'yacybot', 'https://developers.google.com/+/web/snippet/',
75                 'Scrapy/', 'github-camo', 'MJ12bot/', 'DotBot/', 'Pinterestbot/', 'Jooblebot/',
76                 'Cliqzbot/', 'YaK/', 'Mediatoolkitbot', 'Snacktory', 'FunWebProducts', 'oBot/',
77                 '7Siters/', 'KOCMOHABT', 'Google-SearchByImage', 'FemtosearchBot/',
78                 'HubSpot Crawler', 'DomainStatsBot/', 'Re-re Studio'];
79
80         if (!Config::get('blockbot', 'good_crawlers')) {
81                 $agents = array_merge($agents, $good_agents);
82         }
83
84         if (Config::get('blockbot', 'block_gab')) {
85                 $agents[] = 'GabSocial/';
86         }
87
88         foreach ($agents as $agent) {
89                 if (stristr($_SERVER['HTTP_USER_AGENT'], $agent)) {
90                         System::httpExit(403, 'Bots are not allowed');
91                 }
92         }
93
94         // This switch here is only meant for developers who want to add more bots to the list above, it is not safe for production.
95         if (!Config::get('blockbot', 'training')) {
96                 return;
97         }
98
99         $crawlerDetect = new CrawlerDetect();
100
101         if (!$crawlerDetect->isCrawler()) {
102                 logger::debug('Good user agent detected', $logdata);
103                 return;
104         }
105
106         // List of false positives' strings of known "good" agents.
107         $agents = ['curl', 'zgrab', 'Go-http-client', 'curb', 'github.com', 'reqwest', 'Feedly/',
108                 'Python-urllib/', 'Liferea/', 'aiohttp/', 'WordPress.com Reader', 'hackney/',
109                 'Faraday v', 'okhttp', 'UniversalFeedParser', 'PixelFedBot', 'python-requests',
110                 'WordPress/', 'http.rb/', 'Apache-HttpClient/', 'WordPress.com;', 'Pleroma',
111                 'Dispatch/', 'Ruby', 'Java/', 'libwww-perl/', 'Mastodon/',
112                 'lua-resty-http/'];
113
114         if (Config::get('blockbot', 'good_crawlers')) {
115                 $agents = array_merge($agents, $good_agents);
116         }
117
118         foreach ($agents as $agent) {
119                 if (stristr($_SERVER['HTTP_USER_AGENT'], $agent)) {
120                         logger::notice('False positive', $logdata);
121                         return;
122                 }
123         }
124
125         logger::info('Blocked bot', $logdata);
126         System::httpExit(403, 'Bots are not allowed');
127 }