]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/RegisterThrottle/RegisterThrottlePlugin.php
[TRANSLATION] Update license and copyright notice in translation files
[quix0rs-gnu-social.git] / plugins / RegisterThrottle / RegisterThrottlePlugin.php
1 <?php
2 /**
3  * StatusNet - the distributed open-source microblogging tool
4  * Copyright (C) 2010, StatusNet, Inc.
5  *
6  * Throttle registration by IP address
7  *
8  * PHP version 5
9  *
10  * This program is free software: you can redistribute it and/or modify
11  * it under the terms of the GNU Affero General Public License as published by
12  * the Free Software Foundation, either version 3 of the License, or
13  * (at your option) any later version.
14  *
15  * This program is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18  * GNU Affero General Public License for more details.
19  *
20  * You should have received a copy of the GNU Affero General Public License
21  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
22  *
23  * @category  Spam
24  * @package   StatusNet
25  * @author    Evan Prodromou <evan@status.net>
26  * @copyright 2010 StatusNet, Inc.
27  * @license   http://www.fsf.org/licensing/licenses/agpl-3.0.html AGPL 3.0
28  * @link      http://status.net/
29  */
30
31 if (!defined('GNUSOCIAL')) { exit(1); }
32
33 /**
34  * Throttle registration by IP address
35  *
36  * We a) record IP address of registrants and b) throttle registrations.
37  *
38  * @category  Spam
39  * @package   StatusNet
40  * @author    Evan Prodromou <evan@status.net>
41  * @copyright 2010 StatusNet, Inc.
42  * @license   http://www.fsf.org/licensing/licenses/agpl-3.0.html AGPL 3.0
43  * @link      http://status.net/
44  */
45
46 class RegisterThrottlePlugin extends Plugin
47 {
48     const PLUGIN_VERSION = '2.0.0';
49
50     /**
51      * Array of time spans in seconds to limits.
52      *
53      * Default is 3 registrations per hour, 5 per day, 10 per week.
54      */
55     public $regLimits = array(604800 => 10, // per week
56                               86400 => 5, // per day
57                               3600 => 3); // per hour
58
59     /**
60      * Disallow registration if a silenced user has registered from
61      * this IP address.
62      */
63     public $silenced = true;
64
65     /**
66      * Auto-silence all other users from the same registration_ip
67      * as the one being silenced. Caution: Many users may come from
68      * the same IP (even entire countries) without having any sort
69      * of relevant connection for moderation.
70      */
71     public $auto_silence_by_ip = false;
72
73     /**
74      * Whether we're enabled; prevents recursion.
75      */
76     static private $enabled = true;
77
78     /**
79      * Database schema setup
80      *
81      * We store user registrations in a table registration_ip.
82      *
83      * @return boolean hook value; true means continue processing, false means stop.
84      */
85     public function onCheckSchema()
86     {
87         $schema = Schema::get();
88
89         // For storing user-submitted flags on profiles
90         $schema->ensureTable('registration_ip', Registration_ip::schemaDef());
91         return true;
92     }
93
94     public function onRouterInitialized(URLMapper $m)
95     {
96         $m->connect('main/ipregistrations/:ipaddress',
97                     array('action'      => 'ipregistrations'),
98                     array('ipaddress'   => '[0-9a-f\.\:]+'));
99     }
100
101     /**
102      * Called when someone tries to register.
103      *
104      * We check the IP here to determine if it goes over any of our
105      * configured limits.
106      *
107      * @param Action $action Action that is being executed
108      *
109      * @return boolean hook value
110      */
111     public function onStartRegistrationTry($action)
112     {
113         $ipaddress = $this->_getIpAddress();
114
115         if (empty($ipaddress)) {
116             // TRANS: Server exception thrown when no IP address can be found for a registation attempt.
117             throw new ServerException(_m('Cannot find IP address.'));
118         }
119
120         foreach ($this->regLimits as $seconds => $limit) {
121
122             $this->debug("Checking $seconds ($limit)");
123
124             $reg = $this->_getNthReg($ipaddress, $limit);
125
126             if (!empty($reg)) {
127                 $this->debug("Got a {$limit}th registration.");
128                 $regtime = strtotime($reg->created);
129                 $now     = time();
130                 $this->debug("Comparing {$regtime} to {$now}");
131                 if ($now - $regtime < $seconds) {
132                     // TRANS: Exception thrown when too many user have registered from one IP address within a given time frame.
133                     throw new Exception(_m('Too many registrations. Take a break and try again later.'));
134                 }
135             }
136         }
137
138         // Check for silenced users
139
140         if ($this->silenced) {
141             $ids = Registration_ip::usersByIP($ipaddress);
142             foreach ($ids as $id) {
143                 $profile = Profile::getKV('id', $id);
144                 if ($profile && $profile->isSilenced()) {
145                     // TRANS: Exception thrown when attempting to register from an IP address from which silenced users have registered.
146                     throw new Exception(_m('A banned user has registered from this address.'));
147                 }
148             }
149         }
150
151         return true;
152     }
153
154     function onEndShowSections(Action $action)
155     {
156         if (!$action instanceof ShowstreamAction) {
157             // early return for actions we're not interested in
158             return true;
159         }
160
161         $target = $action->getTarget();
162         if (!$target->isSilenced()) {
163             // Only show the IP of users who are not silenced.
164             return true;
165         }
166
167         $scoped = $action->getScoped();
168         if (!$scoped->hasRight(Right::SILENCEUSER)) {
169             // only show registration IP if we have the right to silence users
170             return true;
171         }
172
173         $ri = Registration_ip::getKV('user_id', $target->getID());
174         $ipaddress = null;
175         if ($ri instanceof Registration_ip) {
176             $ipaddress = $ri->ipaddress;
177             unset($ri);
178         }
179
180         $action->elementStart('div', array('id' => 'entity_mod_log',
181                                            'class' => 'section'));
182
183         $action->element('h2', null, _('Registration IP'));
184
185         // TRANS: Label for the information about which IP a users registered from.
186         $action->element('strong', null, _('Registered from:'));
187         $el = 'span';
188         $attrs = ['class'=>'ipaddress'];
189         if (!is_null($ipaddress)) {
190             $el = 'a';
191             $attrs['href'] = common_local_url('ipregistrations', array('ipaddress'=>$ipaddress));
192         }
193         $action->element($el, $attrs,
194                             // TRANS: Unknown IP address.
195                             $ipaddress ?: _('unknown'));
196
197         $action->elementEnd('div');
198     }
199
200     /**
201      * Called after someone registers, by any means.
202      *
203      * We record the successful registration and IP address.
204      *
205      * @param Profile $profile new user's profile
206      *
207      * @return boolean hook value
208      */
209     public function onEndUserRegister(Profile $profile)
210     {
211         $ipaddress = $this->_getIpAddress();
212
213         if (empty($ipaddress)) {
214             // User registration can happen from command-line scripts etc.
215             return true;
216         }
217
218         $reg = new Registration_ip();
219
220         $reg->user_id   = $profile->getID();
221         $reg->ipaddress = mb_strtolower($ipaddress);
222         $reg->created   = common_sql_now();
223
224         $result = $reg->insert();
225
226         if ($result === false) {
227             common_log_db_error($reg, 'INSERT', __FILE__);
228             // @todo throw an exception?
229         }
230
231         return true;
232     }
233
234     /**
235      * Check the version of the plugin.
236      *
237      * @param array &$versions Version array.
238      *
239      * @return boolean hook value
240      */
241     public function onPluginVersion(array &$versions)
242     {
243         $versions[] = array('name' => 'RegisterThrottle',
244                             'version' => self::PLUGIN_VERSION,
245                             'author' => 'Evan Prodromou',
246                             'homepage' => 'https://git.gnu.io/gnu/gnu-social/tree/master/plugins/RegisterThrottle',
247                             'description' =>
248                             // TRANS: Plugin description.
249                             _m('Throttles excessive registration from a single IP address.'));
250         return true;
251     }
252
253     /**
254      * Gets the current IP address.
255      *
256      * @return string IP address or null if not found.
257      */
258     private function _getIpAddress()
259     {
260         $keys = array('HTTP_X_FORWARDED_FOR',
261                       'HTTP_X_CLIENT',
262                       'CLIENT-IP',
263                       'REMOTE_ADDR');
264
265         foreach ($keys as $k) {
266             if (!empty($_SERVER[$k])) {
267                 return $_SERVER[$k];
268             }
269         }
270
271         return null;
272     }
273
274     /**
275      * Gets the Nth registration with the given IP address.
276      *
277      * @param string  $ipaddress Address to key on
278      * @param integer $n         Nth address
279      *
280      * @return Registration_ip nth registration or null if not found.
281      */
282     private function _getNthReg($ipaddress, $n)
283     {
284         $reg = new Registration_ip();
285
286         $reg->ipaddress = $ipaddress;
287
288         $reg->orderBy('created DESC');
289         $reg->limit($n - 1, 1);
290
291         if ($reg->find(true)) {
292             return $reg;
293         } else {
294             return null;
295         }
296     }
297
298     /**
299      * When silencing a user, silence all other users registered from that IP
300      * address.
301      *
302      * @param Profile $profile Person getting a new role
303      * @param string  $role    Role being assigned like 'moderator' or 'silenced'
304      *
305      * @return boolean hook value
306      */
307     public function onEndGrantRole($profile, $role)
308     {
309         if (!self::$enabled) {
310             return true;
311         }
312
313         if ($role !== Profile_role::SILENCED) {
314             return true;
315         }
316
317         if (!$this->auto_silence_by_ip) {
318             return true;
319         }
320
321         $ri = Registration_ip::getKV('user_id', $profile->getID());
322
323         if (empty($ri)) {
324             return true;
325         }
326
327         $ids = Registration_ip::usersByIP($ri->ipaddress);
328
329         foreach ($ids as $id) {
330             if ($id == $profile->getID()) {
331                 continue;
332             }
333
334             try {
335                 $other = Profile::getByID($id);
336             } catch (NoResultException $e) {
337                 continue;
338             }
339
340             if ($other->isSilenced()) {
341                 continue;
342             }
343
344             // 'enabled' here is used to prevent recursion, since
345             // we'll end up in this function again on ->silence()
346             // though I actually think it doesn't matter since we
347             // do this in onEndGrantRole and that means the above
348             // $other->isSilenced() test should've 'continue'd...
349             $old = self::$enabled;
350             self::$enabled = false;
351             $other->silence();
352             self::$enabled = $old;
353         }
354     }
355 }