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