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