]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/RegisterThrottle/RegisterThrottlePlugin.php
Merge remote-tracking branch 'upstream/master' into social-master
[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 $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->hasRight(Right::SILENCEUSER)) {
159             // only show registration IP if we have the right to silence users
160             return true;
161         }
162
163         $ri = Registration_ip::getKV('user_id', $target->getID());
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         // TRANS: Label for the information about which IP a users registered from.
176         $action->element('strong', null, _('Registered from:'));
177         $el = 'span';
178         $attrs = ['class'=>'ipaddress'];
179         if (!is_null($ipaddress)) {
180             $el = 'a';
181             $attrs['href'] = common_local_url('ipregistrations', array('ipaddress'=>$ipaddress));
182         }
183         $action->element($el, $attrs,
184                             // TRANS: Unknown IP address.
185                             $ipaddress ?: _('unknown'));
186
187         $action->elementEnd('div');
188     }
189
190     /**
191      * Called after someone registers, by any means.
192      *
193      * We record the successful registration and IP address.
194      *
195      * @param Profile $profile new user's profile
196      *
197      * @return boolean hook value
198      */
199     public function onEndUserRegister(Profile $profile)
200     {
201         $ipaddress = $this->_getIpAddress();
202
203         if (empty($ipaddress)) {
204             // User registration can happen from command-line scripts etc.
205             return true;
206         }
207
208         $reg = new Registration_ip();
209
210         $reg->user_id   = $profile->getID();
211         $reg->ipaddress = mb_strtolower($ipaddress);
212         $reg->created   = common_sql_now();
213
214         $result = $reg->insert();
215
216         if ($result === false) {
217             common_log_db_error($reg, 'INSERT', __FILE__);
218             // @todo throw an exception?
219         }
220
221         return true;
222     }
223
224     /**
225      * Check the version of the plugin.
226      *
227      * @param array &$versions Version array.
228      *
229      * @return boolean hook value
230      */
231     public function onPluginVersion(array &$versions)
232     {
233         $versions[] = array('name' => 'RegisterThrottle',
234                             'version' => GNUSOCIAL_VERSION,
235                             'author' => 'Evan Prodromou',
236                             'homepage' => 'http://status.net/wiki/Plugin:RegisterThrottle',
237                             'description' =>
238                             // TRANS: Plugin description.
239                             _m('Throttles excessive registration from a single IP address.'));
240         return true;
241     }
242
243     /**
244      * Gets the current IP address.
245      *
246      * @return string IP address or null if not found.
247      */
248     private function _getIpAddress()
249     {
250         $keys = array('HTTP_X_FORWARDED_FOR',
251                       'HTTP_X_CLIENT',
252                       'CLIENT-IP',
253                       'REMOTE_ADDR');
254
255         foreach ($keys as $k) {
256             if (!empty($_SERVER[$k])) {
257                 return $_SERVER[$k];
258             }
259         }
260
261         return null;
262     }
263
264     /**
265      * Gets the Nth registration with the given IP address.
266      *
267      * @param string  $ipaddress Address to key on
268      * @param integer $n         Nth address
269      *
270      * @return Registration_ip nth registration or null if not found.
271      */
272     private function _getNthReg($ipaddress, $n)
273     {
274         $reg = new Registration_ip();
275
276         $reg->ipaddress = $ipaddress;
277
278         $reg->orderBy('created DESC');
279         $reg->limit($n - 1, 1);
280
281         if ($reg->find(true)) {
282             return $reg;
283         } else {
284             return null;
285         }
286     }
287
288     /**
289      * When silencing a user, silence all other users registered from that IP
290      * address.
291      *
292      * @param Profile $profile Person getting a new role
293      * @param string  $role    Role being assigned like 'moderator' or 'silenced'
294      *
295      * @return boolean hook value
296      */
297     public function onEndGrantRole(Profile $profile, $role)
298     {
299         if (!self::$enabled) {
300             return true;
301         }
302
303         if ($role != Profile_role::SILENCED) {
304             return true;
305         }
306
307         if (!$this->silenced) {
308             return true;
309         }
310
311         $ri = Registration_ip::getKV('user_id', $profile->id);
312
313         if (empty($ri)) {
314             return true;
315         }
316
317         $ids = Registration_ip::usersByIP($ri->ipaddress);
318
319         foreach ($ids as $id) {
320             if ($id == $profile->id) {
321                 continue;
322             }
323
324             $other = Profile::getKV('id', $id);
325
326             if (empty($other)) {
327                 continue;
328             }
329
330             if ($other->isSilenced()) {
331                 continue;
332             }
333
334             $old = self::$enabled;
335             self::$enabled = false;
336             $other->silence();
337             self::$enabled = $old;
338         }
339     }
340 }